gpt4 book ai didi

javascript - 事件和委托(delegate)事件之间的区别?

转载 作者:行者123 更新时间:2023-11-30 15:39:42 24 4
gpt4 key购买 nike

我正在阅读 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是 View 上的函数,被调用以应用来自 events View 属性的事件。

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

关于javascript - 事件和委托(delegate)事件之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com