简体   繁体   中英

Difference between events and delegateEvents?

I'm reading the docs for Views and I'm confused about what the difference is between events and delegateEvents . They both seem to be called the events method on the View object.

The confusing part to me is what the key should be inside the events hash.

From the docs:

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"}

But events from the standard events are written differently:

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

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

So how are events supposed to be written? Can you combine the two syntaxes?

delegateEvents is the function on the view which is called to apply the events from the events view property.

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.

This is happening inside the setElement function ( line 1273 ):

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

So the syntax is the same and both syntax works.

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
  },
});

Inside the delegateEvents function, the key (eg "keydown .sub-element" ) is split using a regex ( line 1311 ).

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

The regex to split the event from the selector ( line 1227 ):

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

And the delegate function ( 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; }, 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM