2012-02-05 62 views
1

请告诉我,视图内数据处理的最佳做法是什么?在主干视图模板中处理数据的正确方法

例如:我有一个User模型,并且有age字段。在这个领域是一个用户的时代。它是一个整数值 - 数月。而且我怎么能在我的模板实现这一点:

  • 17 => 1年5个月
  • 11 =>11个月
  • 24 => 2年

我在哪里可以存储此辅助性的方法?模板内部是不正确的方式。否则,我需要做一些将生成正确模型json的函数。 (不是model.toJSON())或扩展现有的JSON ...或....

这样做的最佳方法是什么?

谢谢。

回答

1

有两种方法。

你可以把它放在模型上,然后将模型传递给模板 - 这意味着在模板中你必须使用model.get('age')等获得属性,但它也会使有可能为这个模型使用辅助方法。

另一种选择是有某种全球助手收集的那以后,你可以从你的模板访问诸如helpers.verboseAge(age)(不知道什么模板你正在使用这样的脚本也可能是it.age,this.age,年龄...但你的想法

2

我之前给了一个回答类似的问题几个月。 发现它在这个问题backbone toJSON with helper methods

它归结为添加方法的JSON,你去之前模板

是这样的:

var userModel = Backbone.Model.extend({ 
    initialize: function(){ 
     _.bindAll(this, 'fullname', 'toFullJSON'); 
    }, 
    fullname: function(){ 
     return this.get('name') + " " + this.get('lastname'); 
    }, 
    toFullJSON: function(){ 
     var json = this.toJSON(); 
     return _.extend(json, {fullname : this.fullname()}); 
    } 
}); 

var user = new userModel(); 
user.set({name: 'John', lastname: 'Doe'}); 

// you will see in this console log, that the toFullJSON function returns both the toJSON properties, and your added propert(y)(ies)... 
console.log(user.toFullJSON()); 

你可以做的另一件事是覆盖的toJSON方法

这样的:

var myModel = Backbone.Model.extend({ 
    // other methods and functions go here... 

    toJSON: function (attr) { 
    var defaultJSON = Backbone.Model.prototype.toJSON.call(this, attr) 
    return _.extend(defaultJSON, {calculateAge : this.calculateAge()}); 
    }, 

    calculateAge: function(){ 
    // here you calculate the years and what not, then return it. 
    } 
}); 

,做这将是给模型到您的模板代替的第三条道路。 toJSON()返回。那么你可以在你的模板中调用model.CalculateAge()。

相关问题