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");
}
});
Usually you'll call toJSON
on your models to serialize them for use by a template:
var html = template({ person: person.toJSON() })
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.
You could provide your own toJSON
:
toJSON: function() {
var j = _(this.attributes).clone();
j.FullName = this.FullName();
return j;
}
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() });
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…