如何根据集合属性设置Backbone模型的默认值 [英] How to set Backbone model's defaults based on collection attribute
本文介绍了如何根据集合属性设置Backbone模型的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要所有新的MenuItem模型从父系列中获取菜单属性。
这是一个不起作用的基本示例(因为在MenuItem的默认函数中未定义this.collection)
I need all new MenuItem models to have menu attribute from parent collection. Here is a basic example that doesn't work (because this.collection is undefined in MenuItem's defaults function)
var MenuItem, Menu, menu;
MenuItem = Backbone.Model.extend({
defaults: function() {
return {
menu: this.collection.name
}
},
// Fake Backbone sync
sync: function(method, model, options) {
if(typeof model.cid != 'undefined') {
var cid = model.cid;
model.unset('cid').set({id:cid}, {silent:true});
}
options.success(model);
}
});
Menu = Backbone.Collection.extend({
model: MenuItem,
initialize: function(options) {
this.name = options.name;
}
});
menu = new Menu({name: "footer"});
menu.create({title: "Page", url: "/page"}, {
success: function(model){
console.log(model.get("menu")) // expect to be "footer"
}
})
推荐答案
我已经设法通过重写集合的创建方法来修复它,我仍然不确定这是否是正确的方法。
I've managed to fix it by overriding collection's create method, I'm still unsure if this is the right way to go.
create: function(attributes, options) {
return Backbone.Collection.prototype.create.call(
this,
_.extend({menu: this.name}, attributes),
options
);
}
这篇关于如何根据集合属性设置Backbone模型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文