事件和委托事件之间的区别?

Difference between events and delegateEvents?

我正在阅读 docs for Views,我对 eventsdelegateEvents 之间的区别感到困惑。它们似乎都被称为 View 对象的 events 方法。

令我困惑的部分是 events 散列中的密钥。

来自文档:

delegateEvents([events]) Uses jQuery's on function to provide declarative callbacks for DOM events within a view. If an events hash is not passed directly, uses this.events as the source. Events are written in the format {"event selector": "callback"}

但是标准事件中的事件写法不同:

var InputView = Backbone.View.extend({
  tagName: 'input',

  events: {
    "keydown" : "keyAction",   
  },

那么应该如何编写事件?你能把这两种语法结合起来吗?

delegateEvents 是视图上的函数,它被调用以应用来自 events 视图 属性.

的事件

Omitting the selector causes the event to be bound to the view's root element (this.el). By default, delegateEvents is called within the View's constructor for you, so if you have a simple events hash, all of your DOM events will always already be connected, and you will never have to call this function yourself.

这发生在 setElement function (line 1273):

setElement: function(element) {
  this.undelegateEvents();
  this._setElement(element);
  this.delegateEvents();
  return this;
},

所以语法是一样的,两种语法都有效。

var InputView = Backbone.View.extend({
  events: {
    // keydown event from ".sub-element", which must be a child of the view's root
    "keydown .sub-element" : "keyAction", 
    "keydown" : "keyAction", // keydown event from the root element
  },
});

delegateEvents 函数中,key(例如 "keydown .sub-element")使用正则表达式 (line 1311) 拆分。

var match = key.match(delegateEventSplitter);
this.delegate(match[1], match[2], _.bind(method, this));

从选择器中拆分事件的正则表达式 (line 1227):

// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;

delegate函数(line 1317):

// Add a single event listener to the view's element (or a child element
// using `selector`). This only works for delegate-able events: not `focus`,
// `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
delegate: function(eventName, selector, listener) {
  this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
  return this;
},