监听模型属性的特定值更改

时间:2014-04-13 09:25:37

标签: events backbone.js

当我的某个模型属性更改为特定值时,我想触发一个方法。我怎么能这样做?

Person = Backbone.Model.extend({

    defaults: {
        name: 'John',
        age: 34
    },

    initialize: function(){
        this.on('change:age>100', this.die, this); // Here listen for specific value change
    },

    die: function(){
        alert('He had a good run');
    }
});

1 个答案:

答案 0 :(得分:1)

没有内置的Backbone功能。但你可以自己简单地做。这是一个简单的解决方案:

var Person = Backbone.Model.extend({

    defaults: {
        name: 'John',
        age: 34
    },

    initialize: function(){
        this.on('change:age', this.onChangeAge, this); // Here listen for specific value change
    },

    onChangeAge: function(model, newAge){
      if(newAge > 100){
        this.die();
      }
    },

    die: function(){
        alert('He had a good run');
    }
});

或者稍微复杂一些:

var onGreaterThan = function(value, func){
  return function(model, newValue){
    if (newValue > value){
      func.apply(this, arguments);
    }    
  };
};

var Person = Backbone.Model.extend({

    defaults: {
        name: 'John',
        age: 34
    },

    initialize: function(){
        this.on('change:age', onGreaterThan(100, this.die), this); // Here listen for specific value change
    },

    die: function(){
        alert('He had a good run');
    }
});