Access Nested Backbone Model Attributes from Mustache Template

后端 未结 4 790
不思量自难忘°
不思量自难忘° 2020-12-28 21:50

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.

P         


        
4条回答
  •  伪装坚强ぢ
    2020-12-28 22:27

    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(); });
      }
    });
    

提交回复
热议问题