Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Nested Backbone Model Attributes from Mustache Template

I have one Backbone model which has an attribute that is a reference to another Backbone model. For example, a Person has a reference to an Address object.

Person
  FirstName
  LastName
  Address
    Street
    City
    State
    Zip

These are classes that extend the Backbone model. So, then if I construct an object like the following...

var address = new Address({ Street: "123 Main", City: "Austin" });
var person = new Person({ FirstName: "John", Address: address });

I cannot seem to figure out how to access it in my Mustache template.

Hi {{FirstName}}, you live in {{Address.City}}.

Obviously does not work. When I look at the internals in Firebug, Address is an object, but the City is an attribute within the attributes object of Address. I cannot find any examples of how to access these attributes of associated objects.

I appreciate any help! Thanks!

like image 213
Kevin Avatar asked Jun 04 '11 01:06

Kevin


2 Answers

I ended up solving this issue with the following approach.

I switched from Mustache.js to Handlebars.js for the templating engine. This allowed me to use path based expressions to access nested or associated objects and their attributes.

Hi {{FirstName}}. You live in {{Address.City}}.

But, I also had to change the way I was passing a JSON object to the template. I was using the toJSON method that is part of the Backbone.Model class. But, this was not generating JSON for the associated Address correctly (for the templating to work.) It was burying the address attributes in a member titled "attributes". So, instead, I ended up doing this...

var jsonForTemplate = JSON.parse(JSON.stringify(person));

This gave me a "raw" version of the objects and their associated objects which the template could access using the syntax shown above. JSON.parse and JSON.stringify are both part of json2.js.

like image 91
Kevin Avatar answered Jan 04 '23 12:01

Kevin


I handled this by making another version of toJSON called deepToJSON that recursively traverses nested models and collections. The return value of that function can then be passed to a handlebars.js template.

Here is the code:

_.extend(Backbone.Model.prototype, {
  // Version of toJSON that traverses nested models
  deepToJSON: function() {
    var obj = this.toJSON();
    _.each(_.keys(obj), function(key) {
      if (_.isFunction(obj[key].deepToJSON)) {
        obj[key] = obj[key].deepToJSON();
      }
    });
    return obj;
  }
});

_.extend(Backbone.Collection.prototype, {
  // Version of toJSON that traverses nested models
  deepToJSON: function() {
    return this.map(function(model){ return model.deepToJSON(); });
  }
});
like image 24
gregspurrier Avatar answered Jan 04 '23 12:01

gregspurrier