sub*_*ime 18 javascript backbone.js underscore.js backbone.js-collections
我知道使用pluck方法我们可以获得骨干集合中每个模型的一系列属性
var idsInCollection = collection.pluck('id'); // outputs ["id1","id2"...]
Run Code Online (Sandbox Code Playgroud)
我想如果有一个方法为集合中的每个模型设置属性,
var urlArray = ["https://url1", "https://url1" ...];
collection.WHAT_IS_THIS_METHOD({"urls": urlArray});
Run Code Online (Sandbox Code Playgroud)
mac*_*ost 39
这并不是一个预先存在的方法,但invoke让我们在一行中做类似的事情:
collection.invoke('set', {"urls": urlArray});
Run Code Online (Sandbox Code Playgroud)
如果要在所有集合上创建可重用的set方法,可以执行以下操作:
var YourCollection = Backbone.Collection.extend({
set: function(attributes) {
this.invoke('set', attributes);
// NOTE: This would need to get a little more complex to support the
// set(key, value) syntax
}
});
Run Code Online (Sandbox Code Playgroud)
*编辑*
Backbone已经添加了自己的set方法,如果你覆盖它,你将彻底打破你的Collection.因此,上面的例子应该真正重命名为setModelAttributes,或者其他任何不重命名的例子set.
我没有它的方法,但你可以尝试:
collection.forEach(function(model, index) {
model.set(url, urlArray[index]);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18759 次 |
| 最近记录: |