Backbone.js源代码 - eventsApi

时间:2017-07-02 21:46:06

标签: javascript backbone.js

以下是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

1 个答案:

答案 0 :(得分:3)

上面的迭代内容如下:

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对象。这是递归的常见用法。