简体   繁体   中英

Backbone collection change event on model

Is it possible to listen for a change in a model in a collection if a specific field is changed to a specific value?

I know that something like 'change:fieldName' exists, I'm looking for something like 'changeTo: fieldName = true'

There's not a "shortcut" way of doing so. You have to listen to the normal change event, and in your listener, see if the value has changed to something interesting for you. Then, propagate the event, fire a new one, or do stuff.

Backbone.Collection.extend({

    initialize: function() {
        this.on('change:property', this.onChange);
    },

    onChange: function(e) {
        // sorry for pseudo-code, can't remember syntax by heart, will edit
        if (e.newValue == true)
            myLogic();
    }

}

You cannot listen for an explicit value since that wouldn't work well in the general case, but you can easily bind to the general handler and run your code based on that.

var MyCollection = Backbone.Collection.extend({
  initialize: function(models, options){
    this.on('change:myProperty', this.changeMyProperty_, this);
  },

  changeMyProperty_: function(model, value){
    if (value) this.myPropertyTrue_(model);
  },

  myPropertyTrue_: function(model){
    // Do your logic
  }
});

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