copenndthagen
copenndthagen

Reputation: 50790

Retrieve Backbone Model value

Is there a more efficient way of writing the statement below to access Backbone Model value?

self.model.attributes.person.attributes.personName

Also while the above works fine in a JS file, it does not work within my HTML template file

<%= self.model.attributes.person.attributes.personName %>

I use below code to call template;

this._initAndRenderModal(myModalTemplate, {
    person: this.model.toJSON()
});

How do I make it retrieve value within my HTML file as well?

Upvotes: 0

Views: 53

Answers (3)

lexeme
lexeme

Reputation: 2973

Show more code, please. What is person? If it's a complex/nested backbone model (like person has person relation) then you can try this:

var name = model.get('person').get('personName');

You can use model.get('propertyName') to access model's properties. When you call

this.template({model: templateData})

it is expected that you export model object as a reference to your template data so you would write it like this inside your template:

<%= model.get('property') %> <-- given that model is a backbone Model 

or

<%= model.get('complexProperty').partOfTheComplexProperty %> <-- given that model is a backbone Model 

or

<%= model.anythingYouWant %>

Upvotes: 1

Kiril
Kiril

Reputation: 2963

To get name you may use (read more about get: http://backbonejs.org/#Model-get)

self.model.get("person").get("personName")

To render the template correctly it should be

<%= person.attributes.personName %>

as you pass this.model.toJSON() to it - there's no need to point to the model itself.

Upvotes: 0

jgillich
jgillich

Reputation: 76369

That depends entirely on how you render it, but this should work:

_.template('<%= model.attributes.person.attributes.personName %>', { model: self.model });

I would also recommend using toJSON instead of accessing the attributes: http://backbonejs.org/#Model-toJSON

Upvotes: 0

Related Questions