alloy Model: 数据绑定(data binding) 5 - 终极总结,前面的都不用看了.
访问量: 2698
refer to: (直接看这里就可以了, 好多的例子,代码很简单) https://github.com/appcelerator/alloy/tree/master/test/apps/models
直接看上面的链接. 下面的看一下即可. 没有经过严谨的测试,不保证通过.
总结的话,就是:
不需要把数据保存到DB的情况:
在alloy.js 中:
Alloy.Models.book = new Backbone.Model({
title: 'default title'
})
在controller中:
book = Alloy.Models.book;
function update_title(e){
book.set('title', Math.random() )
}
$.index.open()
//记得这里不要用 fetch(), 否则会报错. 因为这个model没有对应到数据库
// 记得务必要用 trigger('change'), 否则这个值在页面首次打开时不会显示出来.
book.trigger('change')
在 view中:
<Alloy>
<!-- 这里记得不需要用这个标签!
<Model src='book' />
-->
<Label id='book_title' text="{book.title}" onClick="update_title" />
</Alloy>
需要保存数据的情况:
参考: https://github.com/appcelerator/alloy/tree/master/test/apps/models/binding_listview
1. 记得声明个model:
//migration, db_name, db_file 也是可以配置的
exports.definition = {
config: {
'columns': {
'title' : 'TEXT',
'id' : 'INTEGER PRIMARY KEY AUTOINCREMENT'
},
'adapter': {
'type': 'sql',
'collection_name': 'books',
'idAttribute': 'id',
//'migration': '20150404180000'
}
},
extendModel: function(Model){
_.extend(Model.prototype, {});
return Model;
},
extendCollection: function(Collection){
_.extend(Collection.prototype, {});
return Collection;
}
}
2. 在XML中要有 <Model/> 或者 <Collection /> 标签
<Alloy>
<Window class="container">
<Label text='lalala' />
<ListView id='list' defaultItemTemplate='title'>
<Templates>
<ItemTemplate name='title_template' height='50'>
<Label bindId='id' left='20' />
<Label bindId='title' left='40'/>
</ItemTemplate>
</Templates>
<ListSection id='section' dataCollection='books'>
<ListItem template='title_template' title:text="{title}" id:text="{id}" />
</ListSection>
</ListView>
</Window>
</Alloy>
3. alloy.js :
Alloy.Collections.book = Alloy.createCollection('book')
var book = Alloy.createCollection('book')
4. index.js:
books = Alloy.Collections.books books.fetch() $.index.open()