Backbone.js - 如何在模板中使用自定义模型属性?

boo*_*ean 7 javascript backbone.js handlebars.js

这可能是一个非常简单的问题,但我很想找到答案.

使用骨干,我有这条线:

Person = Backbone.Model.extend();
Run Code Online (Sandbox Code Playgroud)

然后我在从URL填充的集合中使用它.为了这个例子,假设我有名字和姓,我想做的事情如下:

Person = Backbone.Model.extend({
    FullName: this.get("firstName") + " " + this.get("lastName")
});
Run Code Online (Sandbox Code Playgroud)

我可以使用例如People.first().FullName()来调用内部主干.但是如果我将People.first()传递给我的视图并在模板中呈现它,它似乎不知道FullName是什么.

如何在Backbone中为模型添加自定义属性并在模板中使用?

干杯!

mu *_*ort 14

你的FullName定义没有任何意义所以我会假设你真的是这个意思:

Person = Backbone.Model.extend({
    FullName: function() {
        return this.get("firstName") + " " + this.get("lastName");
    }
});
Run Code Online (Sandbox Code Playgroud)

通常,您会调用toJSON模型来序列化它们以供模板使用:

var html = template({ person: person.toJSON() })
Run Code Online (Sandbox Code Playgroud)

默认情况下toJSON只返回模型的内部属性的(浅)副本.据推测,属性可以同时具有属性firstNamelastName属性,但它FullName是模型上的一个函数,因此它不属于属性.

你可以提供自己的toJSON:

toJSON: function() {
    var j = _(this.attributes).clone();
    j.FullName = this.FullName();
    return j;
}
Run Code Online (Sandbox Code Playgroud)

然后你FullName的模板中有一个.但是,toJSON也用于序列化模型以将数据发送到服务器; 你的服务器最终会看到它FullName,它可能会对此感到不安.您可以专门为模板添加另一个序列化程序:

// `serialize` is another common name for this
for_template: function() {
    var j = this.toJSON();
    j.FullName = this.FullName();
    return j;
}
Run Code Online (Sandbox Code Playgroud)

然后使用该函数为模板提供数据:

var html = template({ person: person.for_template() });
Run Code Online (Sandbox Code Playgroud)

  • 完全同意,我首选的方法是`for_template`,我不喜欢用非常核心的方法来理解`toJSON`.相关回答http://stackoverflow.com/questions/9642439/computed-properties-in-backbone/9687672#9687672 (2认同)