【问题标题】:Bind model change event to specific properties only仅将模型更改事件绑定到特定属性
【发布时间】:2016-06-30 13:41:24
【问题描述】:

假设我想要两个事件侦听器,一个用于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),另一个用于其余属性,在第二个事件监听器中,我正在检查更新的属性是否不是myAttribute,以避免触发 2 个事件。

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

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

任何建议将不胜感激。

【问题讨论】:

  • 那么当包括myAttribute在内的一堆属性同时改变时会发生什么?
  • @TJ 一个好问题,在这种情况下,其他属性将由另一个事件侦听器处理,myAttribute 将仅由其事件侦听器处理。

标签: javascript events backbone.js model bind


【解决方案1】:

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

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2013-07-29
    • 2014-09-27
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多