以下是Backbone.js注释源代码的摘录:
var eventsApi = function(iteratee, events, name, callback, opts) {
var i = 0, names;
if (name && typeof name === 'object') {
if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
for (names = _.key(names); i < names.length; i++) {
events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
}
} else if (name && eventSplitter.test(name)) {
for (names = name.split(eventSplitter); i < names.length; i++) {
events = iteratee(events, names[i], callback, opts);
}
} else {
events = iteratee(events, name, callback, opts);
}
return events;
};
eventsApi
函数将事件作为对象进行检查,以便处理jQuery样式的事件映射。但是,为什么在遍历所有事件时递归调用
eventsApi
? 最佳答案
上面的iteratee如下:
var onApi = function(events, name, callback, options) {
if (callback) {
var handlers = events[name] || (events[name] = []);
var context = options.context, ctx = options.ctx, listening = options.listening;
if (listening) listening.count++;
handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
}
return events;
};
它为单个属性(
name
)注册一个事件。eventsApi
检查第二个参数是否是一个对象,在这种情况下,它会调用自身以注册该对象的所有属性(例如模型的attributes
对象)的事件。这是递归的常见用法。