Sencha Touch 2 使用视图.docx
- 文档编号:23107783
- 上传时间:2023-04-30
- 格式:DOCX
- 页数:14
- 大小:23.23KB
Sencha Touch 2 使用视图.docx
《Sencha Touch 2 使用视图.docx》由会员分享,可在线阅读,更多相关《Sencha Touch 2 使用视图.docx(14页珍藏版)》请在冰豆网上搜索。
SenchaTouch2使用视图
前言:
视图[View]是MVC应用程序的脸面,不管你的应用程序设计如何,用户都只能看到眼前的视图,因此对你的评价也只能通过对视图的体验来得到。
因此无论如何,一定要用心去设计你的视图。
这篇文章的英文原址是
原文标题是:
UsingViewsinyourApplications(在应用程序中使用视图)。
在官方文档目录中,它事实上的地位是MVC概述之后开篇三板斧之一,鉴于SenchaTouchMVC的特点,这三板斧的介绍顺序是倒过来的,先C控制器再V视图最后才是M数据模型,但是其重要性却不分先后。
SenchaTouch交流QQ群213119459欢迎您的加入。
UsingViewsinyourApplications
在应用程序中使用视图
注:
为方便起见,文中所有出现SenchaTouch的地方均以ST简写替代。
Fromtheuser'spointofview,yourapplicationisjustacollectionofviews.AlthoughmuchofthevalueoftheappisintheModelsandControllers,theViewsarewhattheuserinteractswithdirectly.Inthisguidewe'regoingtolookathowtocreatetheviewsthatbuildyourapplication.
从用户的视角来看,你的应用程序就是一堆视图的集合,尽管应用程序大部分有价值的东西都在数据模型和控制器里,但视图才是直接跟用户互动的东西。
这篇指南将带我们学习如何创建视图来搭建应用程序。
UsingExistingComponents
使用现存组件
TheeasiestwaytocreateaviewistojustuseExt.createwithanexistingComponent.Forexample,ifwewantedtocreateasimplePanelwithsomeHTMLinsidewecanjustdothis:
最简单的方法是使用Ext.create来创建一个ST中现存的内置组件,这同样也是一个视图。
例如我们只想要创建一个包含简单html代码的Panel,我们可以这么做:
Ext.create('Ext.Panel',{
html:
'Welcometomyapp',
fullscreen:
true
});
ThissimplycreatesaPanelwithsomehtmlandmakesitfillthescreen.Youcancreateanyofourbuilt-incomponentsthiswaybutbestpracticeistocreateasubclasswithyourspecializationsandthencreatethat.Thankfullythat'ssimpletoo:
上述例子将会创建一个包含html代码的Panel并使其充满屏幕。
你可以用这种方法创建任意内置组件,不过最好的方式还是专门创建一个(内置组件的)子类,然后再来创建这个(定制后的)子类的实例。
幸好这也不是什么麻烦事儿。
Ext.define('MyApp.view.Welcome',{
extend:
'Ext.Panel',
config:
{
html:
'Welcometomyapp',
fullscreen:
true
}
});
Ext.create('MyApp.view.Welcome');
Theoutcomeisthesame,butnowwehaveabrandnewcomponentthatwecancreateanynumberoftimes.Thisisthepatternwe'llnormallywanttofollowwhenbuildingourapp-createasubclassofanexistingcomponentthencreateaninstanceofitlater.Let'stakealookthroughwhatwejustchanged:
上述代码的结果是一样的,但是我们现在有了一个自己命名的新组件,而且以后我们还可以多次使用这个新组件。
这才是我们推荐的应用开发模式:
创建一个现存组件的子类然后再创建该子类的实例。
我们来看一下这种方式跟前面相比有哪些变化:
●Ext.defineallowsustocreateanewclass,extendinganexistingone(Ext.Panelinthiscase)
Ext.define允许我们通过继承一个存在的类(此例中是Ext.Panel)来创建一个新类。
●WefollowedtheMyApp.view.MyViewconventionforournewviewclass.Youcannameitwhateveryoulikebutwesuggeststickingwithconvention
遵循MyApp.view.MyView的常规来给新视图命名,我们也推荐你这样做,而不要随心所欲
●Wedefinedconfigforthenewclassinsideaconfigobject
我们使用config对象为新类定义它自己的参数
AnyoftheconfigoptionsavailableonExt.Panelcannowbespecifiedineitherournewclass'sconfigblockorwhenwecometocreateourinstance.Whendefiningasubclassbesuretousetheconfigobject,whencreatingjustpassinanobject.
此时Ext.Panel的所有有效config属性都可以在新类的config配置块中进行定义或者在创建实例时传入使用了。
定义子类的时候务必使用config对象(其实就是用{}包裹的一系列配置参数的集合),创建的时候也可以传入一个config对象集合。
Forexample,here'sthesamecodeagainbutwithadditionalconfigurationpassedinwithourExt.createcall:
下面的例子只在刚才代码基础之上,在Ext.create时传入了一个新的配置参数。
Ext.define('MyApp.view.Welcome',{
extend:
'Ext.Panel',
config:
{
html:
'Welcometomyapp',
fullscreen:
true
}
});
Ext.create('MyApp.view.Welcome',{
styleHtmlContent:
true
});
ARealWorldExample
一个更贴近现实的例子
ThisisoneoftheviewclassesfromourTwitterapp:
这个视图类来自于我们的Twitter应用:
Ext.define('Twitter.view.SearchBar',{
extend:
'Ext.Toolbar',
xtype:
'searchbar',
requires:
['Ext.field.Search'],
config:
{
ui:
'searchbar',
layout:
'vbox',
cls:
'big',
items:
[
{
xtype:
'title',
title:
'TwitterSearch'
},
{
xtype:
'searchfield',
placeHolder:
'Search...'
}
]
}
});
Thisfollowsthesamepatternasbefore-we'vecreatedanewclasscalledTwitter.view.SearchBar,whichextendstheframework'sExt.Toolbarclass.Wealsopassedinsomeconfigurationoptions,includingalayoutandanitemsarray.
它遵循前面提到的规则,创建了一个继承框架Ext.Toolbar类的新子类,命名为Twitter.view.SearchBar,我们给它传入一些配置参数,其中包含了一个layout属性和items数组。
We'veusedacoupleofnewoptionsthistime:
这次我们使用了两个新的参数:
●requires-becausewe'reusingasearchfieldinouritemsarray,wetellournewviewtorequiretheExt.field.Searchclass.Atthemomentthedynamicloadingsystemdoesnotrecognizeclassesspecifiedbyxtypesoweneedtodefinethedependencymanually
requires——由于我们在items数组中使用了一个searchfield,因此要告诉视图require(引用)Ext.field.Search类。
之所以要这样做是因为此时的系统自动加载功能还无法通过xtype识别这个类(Twitter.view.SearchBar),所以我们不得不手动定义这个依赖项。
●xtype-givesournewclassitsownxtype,allowingustoeasilycreateitinaconfigurationobject(justlikewedidwithsearchfieldabove)
xtype——给我们的新类一个自己的xtype,这样以后就可以轻松地通过配置参数轻松的创建它了。
Thisallowsustocreateinstancesofournewviewclassinacoupleofways:
以后我们就可以通过两种方式来创建新视图(Twitter.view.SearchBar)的实例了。
//createsastandaloneinstance
//创建一个独立的实例
Ext.create('Twitter.view.SearchBar');
//alternatively,usextypetocreateournewclassinsideaPanel
//或者我们在一个Panel中通过xtype方式来创建它
Ext.create('Ext.Panel',{
html:
'Welcometomyapp',
items:
[
{
xtype:
'searchbar',
docked:
'top'
}
]
});
CustomConfigurationsandBehavior
自定义配置和行为
SenchaTouch2makesextensiveuseoftheconfigurationsystemtoprovidepredictableAPIsandkeepthecodecleanandeasilytestable.Westronglysuggestyoudothesameinyourownclasses.
ST2广泛应用了configuration系统来提供可控性好的API并保持代码简洁和容易测试。
我们强烈建议你在自己的类里面也这么做。
Let'ssayyouwanttocreateaimageviewerthatpopsupinformationabouttheimagewhenyoutaponit.Ouraimistocreateareusableviewthatcanbeconfiguredwiththeimageurl,titleanddescription,anddisplaysthetitleanddescriptionwhenyoutaponit.
假设你要创建一个图片浏览视图,当它被点击的时候会弹出该图片的信息。
那么我们当然希望这个视图有很好的重用性,你可以配置图片url、标题、描述属性,并且当点触的时候会自动把标题和描述弹出来。
MostoftheworkarounddisplayingimagesistakencareofforusbytheExt.Imgcomponent,sowe'llsubclassthat:
Ext.Img组件已经围绕图片展示功能做了大量的工作,因此我们继承它既可:
Ext.define('MyApp.view.Image',{
extend:
'Ext.Img',
config:
{
title:
null,
description:
null
},
//setsupourtapeventlistener
//设置点击事件监听器
initialize:
function(){
this.callParent(arguments);
this.element.on('tap',this.onTap,this);
},
//thisiscalledwheneveryoutapontheimage
//每当你点触屏幕的时候就会调用这个函数
onTap:
function(){
Ext.Msg.alert(this.getTitle(),this.getDescription());
}
});
//createsafullscreentappableimage
//创建一个全屏的可点击的图片
Ext.create('MyApp.view.Image',{
title:
'OrionNebula',
description:
'TheOrionNebulaisratherpretty',
src:
'http:
//apod.nasa.gov/apod/image/1202/oriondeep_andreo_960.jpg',
fullscreen:
true
});
We'readdingtwomoreconfigurationstoourclass-titleanddescription-whichbothstartoffasnull.Whenwecreateaninstanceofournewclasswepassthetitleanddescriptionconfigsinjustlikeanyotherconfiguration.
我们给自己的类增加了两个新的配置参数:
title和description,初始都默认为null。
当我们创建这个新类的实例时,我们可以像传递其他参数一样把这两个参数传递进去。
OurnewbehaviorhappensintheinitializeandonTapfunctions.Theinitializefunctioniscalledwheneveranycomponentisinstantiated,soisagreatplacetosetupbehaviorlikeeventlisteners.Thefirstthingwedoisusethis.callParent(arguments)tomakesurethesuperclass'initializefunctioniscalled.Thisisveryimportant,omittingthislinemaycauseyourcomponentsnottobehavecorrectly.
新定义的动作在初始化和点击的时候发生,initialize函数每当组件实例化的时候都会被调用,所以这个地方用来设置事件侦听器是最合适的。
在这里我们做的第一件事是使用this.callParent(arguments)来确保父类的初始化函数已经被执行。
这很重要,忽略这一步可能会导致你的组件无法正确的工作。
AftercallParent,weaddataplistenertothecomponent'selement,whichwillcallouronTapfunctionwhenevertheelementistapped.AllcomponentsinSenchaTouch2haveanelementpropertythatyoucanuseinthiswaytolistentoeventsontheDOMobjects,addorremovestyling,ordoanythingelseyou'dnormallydotoanExt.dom.Element.
在callParent之后,我们给组件的element增加了一个tap侦听器,当这个element被点击时,onTap函数就会被调用。
ST2的每一个组件都有一个element属性,通过它你可以侦听Dom对象的事件,增删样式,或者做其他你以往用Ext.dom.Element来做的事情。
TheonTapfunctionitselfisprettysimple,itjustusesExt.Msg.alerttoquicklypopupsomeinformationabouttheimage.Notethatourtwonewconfigs-titleanddescription-bothreceivegeneratedgetterfunctions(getTitleandgetDescriptionrespectively),aswellasgeneratedsetterfunctions(setTitleandsetDescription).
onTap函数本身非常简单,它只是使用Ext.Msg.alert来快速弹出一些关于图片的信息。
注意我们的两个新参数title和description都自动获得了其对应的getter方法(getTitle和getDescription),同样还有setter方法(setTitle和setDescription)。
AdvancedConfigurations
高级配置
Whenyoucreateanewconfigurationoptiontoaclass,thegetterandsetterfunctionsaregeneratedforyousoaconfigcalled'border'isautomaticallygivengetBorderandsetBorderfunctions:
当你为类创建一个新的配置参数时,一对getter和setter方法也会被生成,因此一个叫做border的配置参数会自动被给予getBorder和setBorder方法。
Ext.define('MyApp.view.MyView',{
extend:
'Ext.Panel',
config:
{
border:
10
}
});
varview=Ext.create('MyApp.view.MyView');
alert(view.getBorder());//alerts10(弹出10)
view.setBorder(15);
alert(view.getBorder());//nowalerts15(弹出15)
Thegetterandsetteraren'ttheonlyfunctionsthataregenerated,thereareacouplemorethatmakelifeasacomponentauthormuchsimpler-applyBorderandupdateBorder:
除了getter和setter之外还会生成一对让开发者感到很爽的方法,applyBorder和updateBorder:
Ext.define('MyApp.view.MyView',{
extend:
'Ext.Panel',
config:
{
border:
0
},
applyBorder:
function(value){
returnvalue+"pxsolidred";
},
updateBorder:
function(newValue,oldValue){
this.element.setStyle('border',newValue);
}
});
OurapplyBorderfunctioniscalledinternallyanytimetheborderconfigurationissetorchanged,includingwhenthecomponentisfirstinstantiated.Thisisthebestplacetoputanycodethattransformsaninputvalue.Inthiscasewe'regoingtotaketheborderwidthpassedinanreturnaCSSborderspecificationstring.
applyBorder函数会在每次border参数设置或者改变的时候被调用,包括
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Sencha Touch 使用视图 使用 视图
![提示](https://static.bdocx.com/images/bang_tan.gif)