2

如何根据其他模型值获取以下代码以进行默认设置?这大致就是我所拥有的

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
    }
});
4

2 回答 2

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”。

于 2013-03-12T12:44:18.147 回答
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"));
于 2013-03-12T12:48:19.310 回答