我有一个骨干模型和集合。在模型中,定义了默认属性值:
var Person = Backbone.Model.extend({
defaults: {
name: "mark",
middle: "-"
}
});
var People = Backbone.Collection.extend({
model: Person
});
var collection = new People();
collection.add({name: "paul", middle: null});
console.log('collection is ');
console.log(collection);
如果为属性“middle”传入“null”,我想要“中”的默认值,即“ - ”。但是,“null”会覆盖默认值。我该怎么做呢? jsfiddle是here
答案 0 :(得分:2)
最干净的方法可能是添加parse
方法并规范化数据:
var Person = Backbone.Model.extend({
defaults: {
name: 'mark',
middle: '-'
},
parse: function (payload) {
return {
name: payload.name || undefined,
middle: payload.middle || undefined
};
}
});
collection.add({name: "paul", middle: null}, {parse: true});
fetch
从服务器返回时,它会自动通过parse
,并且无需调用传递选项标记。您可以在模型级别或集合级别执行此操作。
答案 1 :(得分:1)
初始化时检查值
initialize: function() {
if (!this.get("middle") || $.trim(this.get("middle") || '') === '') {
this.set({"middle": this.defaults.middle});
}
},