如何根据其他模型值获取以下代码? 这大致是我所拥有的
var Model = Backbone.Model.extend({
defaults:{
name:"",
surname:"",
fullTextString:""
}
});
model = new Model({name"John", surname:"Doe", fullTextString:"John"+" "+"Doe"})
我想要的是:
Backbone.Model.extend({
defaults:{
name:"",
surname:"",
fullTextString:name+" "+surname
}
});
答案 0 :(得分:1)
默认值仅在不设置值时使用,因此无法实现所需。
我会使用以下内容来获得您想要的功能:
var Model = Backbone.Model.extend({
defaults: {
firstName: "",
lastName : ""
},
fullName: function() {
return this.get("firstName") + " " + this.get("lastName");
},
get: function( attr ) {
if ( typeof this[attr] === "function" ) {
return this[attr]();
}
return Backbone.Model.prototype.get.call(this, attr);
}
});
这样您可以通过这种方式初始化模型:
model = new Model({firstName: "John", lastName: "Doe"});
并使用model.get("fullName")
获取名称“John Doe”。
答案 1 :(得分:1)
鉴于您希望其中一个属性是基于传入值的计算值,并且可能是默认值(例如,如果它们指定{surname:“Munsch”}但不提供名称),我认为最简单的方法是添加一个这样的初始化器:
var Model = Backbone.Model.extend({
defaults:{
name:"",
surname:""
},
initialize: function() {
this.set({fullTextString: this.get("name") + " " + this.get("surname")});
}
});
model = new Model({name:"John", surname:"Doe"});
model2 = new Model({surname:"Doe"});
console.log("model fullTextString: ", model.get("fullTextString"));
console.log("model2 fullTextString: ", model2.get("fullTextString"));