如果我有一个绑定到Backbone对象事件的函数,将从另一个上下文块程序流中触发该事件,直到绑定函数执行完毕?
例如,待办事项的集合:
class App.Collections.Todos extends Backbone.Collection
model: App.Models.Todo
initialize: ->
@collection.on 'will_change:selected', @logUnselection, this
@collection.on 'change:selected', @logSelection, this
logUnselection: (todo) ->
for t in @collection.models
console.log "unselected!"
logSelection: (todo) ->
console.log "selected!"
单个待办事项的观点有:
class App.Views.Todo extends Backbone.View
events:
'click': 'select'
select: (e) ->
@model.collection.trigger('will_change:selected', @model)
@model.set(selected: true)
当点击待办事项时,无论logUnselection
中的代码执行多长时间,输出总是如下所示?
unselected!
unselected!
unselected!
unselected!
...
unselected!
selected!
或者在事件触发绑定函数时继续执行,可能导致:
unselected!
unselected!
selected!
unselected!
...
unselected!
答案 0 :(得分:1)
触发器将阻止执行。
从Backbone's annotated source开始,这就是调用触发器时发生的情况。您可以看到triggerEvents函数只是执行此触发器的已注册事件。
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
...
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
}
};