0
たとえば、2つのイベントリスナーを1つはmyAttribute
プロパティ、もう1つはプロパティのプロパティリスナーにしたいとします。この問題を解決するための特定のプロパティへのモデル変更イベントのバインド
、私はこの解決策を考え出した:
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 :) !!!'
ここでは、カスタムプロパティ(myAttribute)用のeventListenersとプロパティの残りの2つのeventListenersを登録しました。また、2番目のイベントリスナーでは、更新されたプロパティがmyAttribute
でないとチェックしています。
このシナリオをカバーするデフォルトの解決策はありますか? このようなもの:
this.listenTo(this,'change!myAttribute',this.listenUnlessOnly);
this.listenTo(this,'change:'+this.get('only'),this.listenOnly);
いずれかの提案があります。
1つだけリスナーを作成するためにしたと思いますか? –
@TJ良い質問ですが、この場合、他の属性は他のイベントリスナーによって処理され、 '' myAttribute''はイベントリスナーのみによって処理されます。 – Ismail