当我向视图添加集合时,如下所示:
var View = new MyCollectionView({ collection: new MyCollection() });
Run Code Online (Sandbox Code Playgroud)
一切都好.我可以在initialize方法中使用此集合(例如,用于绑定事件).但是我该如何添加另一个呢?
我不能这样做:
var View = new MyCollectionView({
collection: new MyCollection(),
secondCollection: new MySecondCollection()
});
Run Code Online (Sandbox Code Playgroud)
从精细手册:
构造函数/初始化
new View([options])有迹象表明,如果获得通过,将直接连接到视图几个特殊的选项:
model,collection,el,id,className,tagName,attributes和events.
所以,如果你创建一个这样的视图:
new View({collection: c})
Run Code Online (Sandbox Code Playgroud)
然后Backbone将自动分配c给视图this.collection.但是如果你创建这样的视图:
new View({collection: c, secondCollection: c2})
Run Code Online (Sandbox Code Playgroud)
然后在View的构造函数中:
initialize: function(options) {
// this.collection will be 'c' from above
// options.secondCollection will be 'c2'
}
Run Code Online (Sandbox Code Playgroud)
所以你可以这样做:
var View = new MyCollectionView({
collection: new MyCollection(),
secondCollection: new MySecondCollection()
});
Run Code Online (Sandbox Code Playgroud)
只要你MyCollectionView有一个initialize方法可以知道如何secondCollection摆脱它的options论点.
打开JavaScript控制台,看看它的作用:
var V = Backbone.View.extend({
initialize: function(options) {
var c1 = options.collection;
var c2 = options.secondCollection;
console.log(this.collection);
console.log(c1);
console.log(c2);
}
});
var view = new V({collection: 1, secondCollection: 2});
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ambiguous/XyeSD/
| 归档时间: |
|
| 查看次数: |
1555 次 |
| 最近记录: |