如何访问从车把模板的骨架模型的计算字段? [英] How to access a calculated field of a backbone model from handlebars template?

查看:78
本文介绍了如何访问从车把模板的骨架模型的计算字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从模板访问计算字段我在模型(Backbone.js的)来实现。
我是否需要总是定义一个帮手呢?

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?

我认为这个问题与我的模型传递到模板的方式做。
如果我通过this.model.toJSON()我有机会获得属性,但不是我在它定义的函数。
如果我通过this.model我直接可以访问该功能,但骨干模式不是属性。

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.

推荐答案

总是传递 this.model.toJSON()到您的模板。

您需要做的就是你的计算值是什么,是覆盖您的toJSON 方法对你的模型。

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

})

现在你已经从由的toJSON 返回的JSON,这意味着你有机会获得 myvalue的访问它在视图中。

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.

这篇关于如何访问从车把模板的骨架模型的计算字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆