backbone toJSON with helper methods

前提是你 提交于 2019-12-05 06:48:22

问题


I have a backbone model with attributes and some helper methods that output something other than the actual attribute (for formatting for example).

However, when I call toJSON, only the attributes are returned, so my mustache templates can't access those helper methods. Is there any way to resolve this? Or is there a different approach I should take?

Is the only way around this to create a formatted version of the attribute and update it each time that attribute changes?


回答1:


Jorge, i would extend the toJSON in my own method, and give that new added json to the template.

like so:

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();
u.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(u.toFullJSON());



回答2:


Make sure that the JSON is correct. If you are returning objects, there may be some back references inside them (they are not supported in JSON and will be probably omitted).



来源:https://stackoverflow.com/questions/8225859/backbone-tojson-with-helper-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!