Computed properties in Backbone

后端 未结 4 1187
暖寄归人
暖寄归人 2020-12-03 05:25

I have a scenario where the data being manipulated on the client is presented and interacted with in a different way than it is represented on the server.

Consider t

4条回答
  •  旧时难觅i
    2020-12-03 06:02

    I am using a combination of the initialize() function together with change event listeners to update derived attributes. The idea is first to compute the attributes on model initialization, and second to let the model listen to its own changes and update the attributes accordingly.

    My solution looks roughly like this:

    MyModel: Backbone.Model.extend({
        initialize: function() {
            this.updateDerivedAttributes();
            this.on('change:start_at', this.updateDerivedAttributes, this);
        },
        updateDerivedAttributes: function() {
            this.set({
                start_date: Utils.dateFromDate( this.get( "start_at" ) ),
                start_time: Utils.timeFromDate( this.get( "start_at" ) ),
                duration: Utils.youGetTheIdea()
            }, {silent:true});
        }
    });
    

提交回复
热议问题