简体   繁体   中英

how to access changed attributes after fetch? backbone.js

I'm using this code to fetch a model from a server:

var id = args.model.get('id');
var options = { 
    action: 'getSubscriber', 
    address: args.model.get('address'),
    silent: true
};

new Subscriber({ id: id }, options).fetch({
    success: function(model, response) {
        console.log(response);
        console.log(model);
    }
});

the response object contains all the data I need whereas model stores the data not as its direct attributes but as changed object. Is it wrong? Usually I access model attributes with help of model.get('name') call. How do I access fresh attributes in that case? Should it be model.changed.thePropertyIwantToAccess ?

You can use this change event

    this.model.on('change', function () {
        var changedAttributes = this.model.changedAttributes();
        //Process the changed attributes
    }, this); 

Bind this events in the initialize function of the View

Ended up with this:

var Subscriber = Backbone.Model.extend({
    defaults: {
        id: null,
        name: null,
        status: null
        // ...
    },
    initialize: function(attributes, options) {
        var _this = this;
        this.options = options || {};                
        this.on('change', function() {
            _this.set(_this.changedAttributes()['0']);
        });
    }
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM