仅将模型更改事件绑定到特定属性

时间:2016-06-30 13:41:25

标签: javascript events backbone.js model bind

假设我想要两个Event侦听器,一个用于myAttribute属性,另一个用于其他属性。

为了解决这个问题,我提出了这个解决方案:

var Model = Backbone.Model.extend({

    defaults:function(){
        return {
                    myAttribute:'',
                    secondAttribute:'',
                    thirdAttribute:'',
                    only:'myAttribute'
        };
    },
    initialize:function(){

        this.listenTo(this,'change',this.listenUnlessOnly);
        this.listenTo(this,'change:'+this.get('only'),this.listenOnly);

    },
    listenUnlessOnly:function(){

        // make sure that attributeName doesn't belong to the list 
        // of updated attributes

        if(_.keys(this.changedAttributes()).indexOf(this.get('only')) === -1)             {
            alert('Another attribute changed');
        }else{
            // the other attribute changed so do nothing                 
        }                     
    },
    listenOnly:function(){            
        alert('Yoli myAttribute changed :) !!!');                
    }
});

var m = new Model();
m.set('username','hi'); // Another attribute changed
m.set('myAttribute','something'); // 'Yoli myAttribute changed :) !!!'

Here is the jsFiddle example

我为自定义属性(myAttribute)注册了两个eventListeners,为其余属性注册了另一个eventListener,在第二个eventlistener中我检查更新的属性是否不是myAttribute以避免触发2事件

是否有默认解决方案来涵盖这种情况? 像这样的东西:

this.listenTo(this,'change!myAttribute',this.listenUnlessOnly);
this.listenTo(this,'change:'+this.get('only'),this.listenOnly);

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为你只需要为所有情况创建一个监听器

this.listenTo(this,'change',function(){
  var obj = this.changedAttributes();
  if(obj['myAttribute']){
    this.listenOnly();
    delete obj.myAttribute;
  }else if(_.keys(obj).length >=1){
    this.listenUnlessOnly();
  }
}.bind(this))