Question

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?

Was it helpful?

Solution

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 }}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top