ExtJS 4 官方指南数据 Data 简体中文版.docx

上传人:b****3 文档编号:4474178 上传时间:2022-12-01 格式:DOCX 页数:14 大小:126.98KB
下载 相关 举报
ExtJS 4 官方指南数据 Data 简体中文版.docx_第1页
第1页 / 共14页
ExtJS 4 官方指南数据 Data 简体中文版.docx_第2页
第2页 / 共14页
ExtJS 4 官方指南数据 Data 简体中文版.docx_第3页
第3页 / 共14页
ExtJS 4 官方指南数据 Data 简体中文版.docx_第4页
第4页 / 共14页
ExtJS 4 官方指南数据 Data 简体中文版.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

ExtJS 4 官方指南数据 Data 简体中文版.docx

《ExtJS 4 官方指南数据 Data 简体中文版.docx》由会员分享,可在线阅读,更多相关《ExtJS 4 官方指南数据 Data 简体中文版.docx(14页珍藏版)》请在冰豆网上搜索。

ExtJS 4 官方指南数据 Data 简体中文版.docx

ExtJS4官方指南数据Data简体中文版

ExtJS4官方指南翻译:

数据Data

数据包加载并保存您的应用程序中的所有数据。

它包括41类,但其中有三个,比其他的都重要 - Model, Store 和 Ext.data.proxy.Proxy。

这些几乎每一个应用程序都会用到。

这三个类还有些支持的卫星类:

Thedatapackageiswhatloadsandsavesallofthedatainyourapplicationandconsistsof41classes,buttherearethreethataremoreimportantthanalltheothers- Model, Store and Ext.data.proxy.Proxy.Theseareusedbyalmosteveryapplication,andaresupportedbyanumberofsatelliteclasses:

1模型和存储ModelsandStores

数据包的核心是Ext.data.Model。

 Model代表应用程序中的一些类型数据 - 例如一个电子商务应用程序可能会有Users,Products和Orders模型。

最简单的一个模型仅仅是一个字段和他们的数据。

我们要看看模型的四个主要部分— Fields, Proxies, Associations 和Validations

Thecenterpieceofthedatapackageis Ext.data.Model.AModelrepresentssometypeofdatainanapplication-forexampleane-commerceappmighthavemodelsforUsers,ProductsandOrders.AtitssimplestaModelisjustasetoffieldsandtheirdata.We’regoingtolookatfouroftheprincipalpartsofModel— Fields, Proxies, Associations andValidations.

让我们看看怎么创建一个Model:

Let'slookathowwecreateamodelnow:

Ext.define('User',{

extend:

'Ext.data.Model',

fields:

[

{name:

'id',type:

'int'},

{name:

'name',type:

'string'}

]

});

Models通常会用到Store,Store基本上是Models实例的一个集合。

建立一个Store和加载其数据很简单:

ModelsaretypicallyusedwithaStore,whichisbasicallyacollectionofModelinstances.SettingupaStoreandloadingitsdataissimple:

Ext.create('Ext.data.Store',{

model:

'User',

proxy:

{

type:

'ajax',

url:

'users.json',

reader:

'json'

},

autoLoad:

true

});

我们配置Store使用AjaxProxy,告诉它加载数据的URL,并用一个Reader解析数据。

在这种情况下,我们的服务器返回JSON,所以我们创建一个JSONReader来读取响应。

Store从URLusers.json中自动加载Usermodel实例集合。

users.jsonURL应该返回一个JSON字符串,看起来像这样:

WeconfiguredourStoretousean AjaxProxy,tellingittheurltoloaddatafromandthe Reader usedtodecodethedata.InthiscaseourserverisreturningJSON,sowe'vesetupa JsonReader toreadtheresponse.Thestoreauto-loadsasetofUsermodelinstancesfromtheurl users.json.The users.json urlshouldreturnaJSONstringthatlookssomethinglikethis:

{

success:

true,

users:

[

{id:

1,name:

'Ed'},

{id:

2,name:

'Tommy'}

]

}

 SimpleStore例子里有现场演示。

Foralivedemopleaseseethe SimpleStore example.

2内联数据Inlinedata

Store也可以载入内联的数据。

在内部,Store转换每个作为data (数据)传递到Model实例的对象:

Storescanalsoloaddatainline.Internally,Storeconvertseachoftheobjectswepassinas data into Model instances:

Ext.create('Ext.data.Store',{

model:

'User',

data:

[

{firstName:

'Ed',lastName:

'Spencer'},

{firstName:

'Tommy',lastName:

'Maintz'},

{firstName:

'Aaron',lastName:

'Conran'},

{firstName:

'Jamie',lastName:

'Avins'}

]

});

InlineData例子

InlineDataexample

3排序和分组SortingandGrouping

Stores能够执行本地排序、过滤和分组,以及支持远程排序,过滤和分组:

Storesareabletoperformsorting,filteringandgroupinglocally,aswellassupportingremotesorting,filteringandgrouping:

Ext.create('Ext.data.Store',{

model:

'User',

sorters:

['name','id'],

filters:

{

property:

'name',

value:

'Ed'

},

groupField:

'age',

groupDir:

'DESC'

});

在我们刚刚创建的Store中,数据将首先由名称,然后由ID进行排序,它会过滤为只包括name为“Ed”的数据,并且数据按照年龄分组降序排列。

通过StoreAPI很容易在任何时间改变排序,过滤和分组。

现场演示,请参阅 SortingGroupingFilteringStore例子。

Inthestorewejustcreated,thedatawillbesortedfirstbynamethenid;itwillbefilteredtoonlyincludeUserswiththename'Ed'andthedatawillbegroupedbyageindescendingorder.It'seasytochangethesorting,filteringandgroupingatanytimethroughtheStoreAPI.Foralivedemo,seethe SortingGroupingFilteringStore example.

4代理Proxies

代理用于Store,处理载入和保存模型数据。

有两种类型的代理:

客户端和服务器端。

客户端代理的例子包括在浏览器的内存和HTML5的本地存储功能可用时。

服务器端代理封装处理一些远程服务器数据,其中包括Ajax,Json和Rest。

ProxiesareusedbyStorestohandletheloadingandsavingofModeldata.TherearetwotypesofProxy:

ClientandServer.ExamplesofclientproxiesincludeMemoryforstoringdatainthebrowser'smemoryandLocalStoragewhichusestheHTML5localstoragefeaturewhenavailable.ServerproxieshandlethemarshalingofdatatosomeremoteserverandexamplesincludeAjax,JsonandRest.

代理可以在Model中直接定义,像这样:

ProxiescanbedefineddirectlyonaModellikeso:

Ext.define('User',{

extend:

'Ext.data.Model',

fields:

['id','name','age','gender'],

proxy:

{

type:

'rest',

url:

'data/users',

reader:

{

type:

'json',

root:

'users'

}

}

});

//UsestheUserModel'sProxy

Ext.create('Ext.data.Store',{

model:

'User'

});

这在两个方面有助于我们。

首先,很可能每个使用Usermodel的Stroe都需要以同样的方式加载数据,这样就使我们避免重复定义每个Stroe的Proxy。

第二,我们现在不需要Store就可以载入和保存模型Model:

Thishelpsusintwoways.First,it'slikelythateveryStorethatusestheUsermodelwillneedtoloaditsdatathesameway,soweavoidhavingtoduplicatetheProxydefinitionforeachStore.Second,wecannowloadandsaveModeldatawithoutaStore:

//GivesusareferencetotheUserclass

varUser=Ext.ModelMgr.getModel('User');

vared=Ext.create('User',{

name:

'EdSpencer',

age:

25

});

//我们能直接保存Ed,而不用把他先加到Store里。

//因为我们配置的RestProxy会自动发POST消息到url/users

//WecansaveEddirectlywithouthavingtoaddhimtoaStorefirstbecausewe

//configuredaRestProxythiswillautomaticallysendaPOSTrequesttotheurl/users

ed.save({

success:

function(ed){

console.log("SavedEd!

HisIDis"+ed.getId());

}

});

//LoadUser1anddosomethingwithit(performsaGETrequestto/users/1)

User.load(1,{

success:

function(user){

console.log("Loadeduser1:

"+user.get('name'));

}

});

也有利用HTML5新功能优势的代理, -LocalStorage 和SessionStorage。

虽然旧的浏览器不支持HTML5的这些新API,但是这个技术前景极好。

TherearealsoProxiesthattakeadvantageofthenewcapabilitiesofHTML5- LocalStorage and SessionStorage.Althougholderbrowsersdon'tsupportthesenewHTML5APIs,they'resousefulthatalotofapplicationswillbenefitenormouslyfromtheirpresence.

ExampleofaModelthatusesaProxydirectly

5关联Associations

Models可以用AssociationsAPI联系在一起。

大多数应用程序处理许多不同的Models,Models几乎都是相关的。

一个博客应用程序可能有User,Post和CommentModel。

用户可以创建文章,文章可以收到评论。

我们可以像这样表达这些关系:

ModelscanbelinkedtogetherwiththeAssociationsAPI.MostapplicationsdealwithmanydifferentModels,andtheModelsarealmostalwaysrelated.AblogauthoringapplicationmighthavemodelsforUser,PostandComment.EachUsercreatesPostsandeachPostreceivesComments.Wecanexpressthoserelationshipslikeso:

Ext.define('User',{

extend:

'Ext.data.Model',

fields:

['id','name'],

proxy:

{

type:

'rest',

url:

'data/users',

reader:

{

type:

'json',

root:

'users'

}

},

hasMany:

'Post'//shorthandfor{model:

'Post',name:

'posts'}

});

Ext.define('Post',{

extend:

'Ext.data.Model',

fields:

['id','user_id','title','body'],

proxy:

{

type:

'rest',

url:

'data/posts',

reader:

{

type:

'json',

root:

'posts'

}

},

belongsTo:

'User',

hasMany:

{model:

'Comment',name:

'comments'}

});

Ext.define('Comment',{

extend:

'Ext.data.Model',

fields:

['id','post_id','name','message'],

belongsTo:

'Post'

});

可以很容易地表达您的应用程序中的不同Models之间的丰富关系。

每个模型可以有任意数量的Associations与其他Models关联,Models可以按照任何的顺序定义。

一旦我们有一个Models的实例,我们可以很容易地遍历相关的数据-例如,如果我们想记录每个文章上给定用户的所有评论,我们可以这样做:

It'seasytoexpressrichrelationshipsbetweendifferentModelsinyourapplication.EachModelcanhaveanynumberofassociationswithotherModelsandyourModelscanbedefinedinanyorder.OncewehaveaModelinstancewecaneasilytraversetheassociateddata-forexample,ifwewantedtologallCommentsmadeoneachPostforagivenUser,wecandosomethinglikethis:

//LoadsUserwithID1andrelatedpostsandcommentsusingUser'sProxy

User.load(1,{

success:

function(user){

console.log("User:

"+user.get('name'));

user.posts().each(function(post){

console.log("Commentsforpost:

"+post.get('title'));

ments().each(function(comment){

console.log(comment.get('message'));

});

});

}

});

在我们上面创建的每一个hasMany关联的结果都会产生一个新的函数添加到Model中。

我们定义UsermodelhasManyPosts,会新增user.posts()函数供我们在上面的代码片段使用。

调用guser.posts()返回Postmodel的 Store配置。

反过来,Postmodel获取comments() 函数是因为我们设置的Comments的hasMany关联。

EachofthehasManyassociationswecreatedaboveresultsinanewfunctionbeingaddedtotheModel.WedeclaredthateachUsermodelhasManyPosts,whichaddedthe user.posts() functionweusedinthesnippetabove.Callinguser.posts() returnsa Store configuredwiththePostmodel.Inturn,thePostmodelgetsa comments() functionbecauseofthehasManyCommentsassociationwesetup.

关联不仅仅用于加载数据–创建新纪录的时候也非常有用:

Associationsaren'tjusthelpfulforloadingdata-they'reusefulforcreatingnewrecordstoo:

user.posts().add({

title:

'ExtJS4.0MVCArchitecture',

body:

'It\'sagreatIdeatostructureyourExtJSApplicationsusingthebuiltinMVCArchitecture...'

});

user.posts().sync();

在这里,我们实例化一个新的Post(文章),user_id字段会自动填充上用户ID。

调用sync()通过其配置的Proxy保存新Post-这又是一个异步操作。

如果你想操作完成时发送通知,也可以添加一个回调(callback)。

HereweinstantiateanewPost,whichisautomaticallygiventheUser'sidintheuser_idfield.Callingsync()savesthenewPostviaitsconfiguredProxy-this,again,isanasynchronousoperationtowhichyoucanpassacallbackifyouwanttobenotifiedwhentheoperationcompleted.

belongsTo关联也可以生成新的Model方法,可以这样使用这些方法:

ThebelongsToassociationalsogeneratesnewmethodsonthemodel,here'showwecanusethose:

//gettheuserreferencefromthepost'sbelongsToassociation

post.getUser(function(user){

console.log('Justgottheuserreferencefromthepost:

'+user.get('name'))

});

//trytochangethepost'suser

post.setUser(100,{

callback:

function(product,operation){

if(operation.wasSuccessful()){

console.log('Post\'suserwasupdated');

}else{

console.log('Post\'susercouldnotbeupdated');

}

}

});

再次,加载函数(getUser)是异步的,需要一个回调函数来获取用户实例。

setUser方法只需更新foreign_key(这里是user_id)为100并保存Postmodel。

像往常一样,可以在已完成保存操作时触发回调-无论成功与否。

Oncemore,theloadingfunction(getUser)isasynchronousandrequiresacallbackfunctiontogetattheuserinstance.ThesetUsermethodsi

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高中教育 > 语文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1