停止应用于骨干中相同事件对象的事件传播

时间:2017-03-21 07:08:42

标签: javascript jquery events backbone.js eventtrigger

我已经将相同的自定义事件应用于骨干中的事件对象,具有2个不同的回调。

var ourObject = {};

_.extend(ourObject, Backbone.Events);
function dancing (msg) { console.log("We are dancing. " + msg); }
function jumping (msg) { console.log("We are jumping. " + msg); }
ourObject.on("move", dancing);
ourObject.on("move", jumping);

当我使用ourObject.trigger("move", "Yeah!");触发移动事件时,它将触发两个回调。

我应该如何防止从第一次回调中触发第二次回调?

1 个答案:

答案 0 :(得分:2)

您可以传递一个包含作为事件对象的标志的对象作为第二个参数:

function dancing(msg, event) {
  console.log(event); // flag: false
  event.flag = true;
  console.log("We are dancing. " + msg);
}

function jumping(msg, event) {
  console.log(event); // flag: true
  if(!event.flag) return;
  console.log("We are jumping. " + msg);
}

ourObject.trigger("move", 'test', {
  flag: false
});

或者您可以简单地执行以下操作:

function dancing (msg) {
  this.dancingTriggered = true;
  console.log("We are dancing. " + msg); 
}
function jumping (msg) {
 if(this.dancingTriggered){
   this.dancingTriggered = false;
   return;
 }
 console.log("We are jumping. " + msg); 
}

或者只使用这些回调范围内的简单变量