1

I have model and submodel:

var Field = Backbone.Model.extend();
var MetaField = Backbone.Model.extend();

var metaField = new MetaField({ title: 'width' });
var field = new Field({ meta: metaField, value: 5});

and I want to render this model via handlebars template(view code is ommited)

Template looks like this :

field: {{ meta.get('title') }} value: {{ value }}

But meta.get causes an error(as I understand there is no ability to call methods in handlebars). How can I render meta attributes? Should I throw MetaField object to template context?

kharandziuk
  • 12,020
  • 17
  • 63
  • 121
  • What's the error saying? How are you passing both models to the view? – Puigcerber Jan 29 '14 at 11:13
  • 1
    The problem is that the toJSON() function doesn't recursively go over sub-models. You'll have to implement that behavior; This will help :) http://stackoverflow.com/questions/17050022/how-to-make-backbones-tojson-function-include-sub-models-and-collections Then you can just access it like so: {{ meta.title }} – oamsel Jan 29 '14 at 16:57

1 Answers1

3

You have to ways of solving this, either in your model on your view, depending on the method you choose it'll change the scope of your change.

1. In your Model

this will always included your meta object in serialized Field object. It'll be used when sending the model to the server or when being rendered in any view.

var Field = Backbone.Model.extend({
   toJSON : function(){
     var json = _.clone(this.attributes);
     if(this.get('meta'){
        json.meta = this.get('meta').toJSON();
     }
     return json;
   }
});

2. In your view

This will only apply to the view and will not effect how the model is rendered by other views or sent to server

 var FieldView = Marionette.ItemView.extend({
  
    //return value of this function is merged with the data
    //that is passed to your template
    templateHelpers: function(){
       return {
          meta: this.model.get('meta').toJSON();
       }
    }

 });

Template

You can use the meta attributes in your template like this,

field: {{ meta.title }} value: {{ value }}

Community
  • 1
  • 1
kay.one
  • 7,622
  • 6
  • 55
  • 74