2014-04-13 54 views
1

我想在我的模型的某個屬性更改爲特定值時觸發方法。我怎樣才能做到這一點?在模型的屬性上傾聽具體的值更改

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

沒有內置的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'); 
    } 
}); 
+1

我想到了類似的事情,但感覺檢查新值的每個時間資源的浪費。想知道Backbone是否可以自己照顧。感謝您的回答! – Westerfaq