Backbone.js once()事件方法:计数器增量示例

时间:2013-08-06 08:44:51

标签: javascript backbone.js

我正在阅读Developing Backbone.js Applications

once()方法的例子,我不明白。这是jsfiddle。运行它并查看控制台日志。看到它打印了两个true

var TodoCounter = { counterA: 0, counterB: 0 };
_.extend(TodoCounter, Backbone.Events);

// Increment counterA, triggering an event
var incrA = function(){ 
  TodoCounter.counterA += 1; 
  TodoCounter.trigger('event'); // ??? What is this for?
};

// Increment counterB
var incrB = function(){ 
  TodoCounter.counterB += 1; 
};

// Use once rather than having to explicitly unbind
// our event listener
TodoCounter.once('event', incrA);
TodoCounter.once('event', incrB); 

// Trigger the event once again
TodoCounter.trigger('event');

// Check out output
console.log(TodoCounter.counterA === 1); // true
console.log(TodoCounter.counterB === 1); // true

TodoCounter.trigger('event')incrA()做了什么吗?我删除它,它似乎没有任何区别。

这本书说它只应该为A和B增加一次。我想我理解TodoCounter.trigger('event')中的incrA()除外。

1 个答案:

答案 0 :(得分:1)

不,你是对的,它什么都不做。我相信它只是指出回调仅在使用once()将其绑定到事件时触发一次。