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();
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")
});
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.
How would I add a custom property to a model in Backbone and use that inside a template?
Cheers!
Your
FullNamedefinition doesn’t make any sense so I’m going to assume that you really meant this:Usually you’ll call
toJSONon your models to serialize them for use by a template:The default
toJSONsimply returns a (shallow) copy of the model’s internal attributes. The attributes will, presumably, have bothfirstNameandlastNameproperties butFullNameis a function on the model so it won’t be in the attributes.You could provide your own
toJSON:and then you’d have a
FullNamein your template. However,toJSONis also used to serialize the model to send data to the server; your server would end up seeing aFullNameand it might get upset about that. You could add another serializer specifically for templates:and then use that function to supply data for your templates: