Backbone.js - 如何在模板中使用自定义模型属性? [英] Backbone.js - How to use a custom model property in a template?
问题描述
这可能是一个非常简单的问题,但我花了很多时间寻找答案.
This might be a really simple question but I'm having a heck of a time finding an answer.
使用主干,我有这条线:
Using backbone, I have this line:
Person = Backbone.Model.extend();
然后我在从 URL 填充的集合中使用它.举个例子,假设我有一个名字和姓氏,我想做这样的事情:
I then use that in a collection filled from a URL. For the sake of the example, say I have a first and last name, and I want to do something like:
Person = Backbone.Model.extend({
FullName: this.get("firstName") + " " + this.get("lastName")
});
我可以使用例如 People.first().FullName() 调用内部主干.但是如果我将 People.first() 传递给我的视图并在模板中呈现它,它似乎不知道 FullName 是什么.
I can call that inside backbone using, for example, People.first().FullName(). But if I pass People.first() to my view and render that in a template, it seems to have no knowledge what FullName is.
如何将自定义属性添加到 Backbone 中的模型并在模板中使用它?
How would I add a custom property to a model in Backbone and use that inside a template?
干杯!
推荐答案
你的 FullName
定义没有任何意义,所以我假设你真的是这个意思:
Your FullName
definition doesn't make any sense so I'm going to assume that you really meant this:
Person = Backbone.Model.extend({
FullName: function() {
return this.get("firstName") + " " + this.get("lastName");
}
});
通常你会在你的模型上调用 toJSON
来序列化它们以供模板使用:
Usually you'll call toJSON
on your models to serialize them for use by a template:
var html = template({ person: person.toJSON() })
默认的 toJSON
只返回一个模型内部属性的(浅)副本.据推测,这些属性将同时具有 firstName
和 lastName
属性,但 FullName
是模型上的一个函数,因此它不会出现在属性中.
The default toJSON
simply returns a (shallow) copy of the model's internal attributes. The attributes will, presumably, have both firstName
and lastName
properties but FullName
is a function on the model so it won't be in the attributes.
您可以提供自己的toJSON
:
toJSON: function() {
var j = _(this.attributes).clone();
j.FullName = this.FullName();
return j;
}
然后你的模板中有一个FullName
.但是,toJSON
也用于序列化模型向服务器发送数据;您的服务器最终会看到 FullName
并且可能会对此感到不安.您可以专门为模板添加另一个序列化程序:
and then you'd have a FullName
in your template. However, toJSON
is also used to serialize the model to send data to the server; your server would end up seeing a FullName
and it might get upset about that. You could add another serializer specifically for templates:
// `serialize` is another common name for this
for_template: function() {
var j = this.toJSON();
j.FullName = this.FullName();
return j;
}
然后使用该函数为您的模板提供数据:
and then use that function to supply data for your templates:
var html = template({ person: person.for_template() });
这篇关于Backbone.js - 如何在模板中使用自定义模型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!