Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a calculated field of a backbone model from handlebars template?

I would like to access the calculated fields I have implemented in the model (backbone.js) from the template. Do I need always to define a helper to do it?

I think the problem has to do with the way I pass the model to the template. If I pass this.model.toJSON() I have access to the properties but not to the functions I have defined in it. If I pass this.model directly I can access the function but not the properties of the backbone model.

like image 450
Juanma Avatar asked May 18 '12 08:05

Juanma


2 Answers

Always pass this.model.toJSON() to your templates.

What you need to do to get your calculated values, is override your toJSON method on your model.


MyModel = Backbone.Model.extend({

  myValue: function(){
    return "this is a calculated value";
  },

  toJSON: function(){
    // get the standard json for the object
    var json = Backbone.Model.prototype.toJSON.apply(this, arguments);

    // get the calculated value
    json.myValue = this.myValue();

    // send it all back
    return json;
  }

})

And now you have access to myValue from the the JSON that is returned by toJSON, which means you have access to it in the view.

The other option, as you mentioned, is to build helper methods and register them with Handlebars. Unless you have some functionality that changes based on how the template is being rendered, and/or what data is being passed to the template, I wouldn't bother with that.

like image 73
Derick Bailey Avatar answered Nov 20 '22 01:11

Derick Bailey


Here is another possibility: (from the model initialize)

initialize: function() {
        this.on("change", function () {
            this.set({ calculatedColumn: this.get("otherColumn") }, { silent: true });
        });
    },

Computed properties in Backbone

like image 4
Curtis Yallop Avatar answered Nov 20 '22 02:11

Curtis Yallop