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

后端 未结 4 1725
遇见更好的自我
遇见更好的自我 2021-02-05 16:01

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 p

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 16:17

    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.

提交回复
热议问题