我还没有看到这个函数的源代码,但我不知道,它是这样工作的:
- 选择可以通过selecotrs元件(S)
- 代表们提供的事件处理程序,他们
- 运行
setInterval
上选择不断取消委托,然后重新委派遍布同一事件
或者有纯粹的JavaScript DOM解释呢?
我还没有看到这个函数的源代码,但我不知道,它是这样工作的:
setInterval
上选择不断取消委托,然后重新委派遍布同一事件 或者有纯粹的JavaScript DOM解释呢?
我想你的问题是关于事件代表团的版本.on
。
在JavaScript中,大多数事件冒泡了在DOM层次。 这意味着,当一个事件可以bubble火灾一个元素,它会冒泡到DOM直到document
级别。
考虑这个基本标记:
<div>
<span>1</span>
<span>2</span>
</div>
现在我们应用事件代表团:
$('div').on('click', 'span', fn);
事件处理程序仅连接到div
元素。 由于span
是内部div
,在跨度任何点击都将泡到div
,发射的div
的click处理程序。 在那一刻,所有剩下的就是检查是否event.target
(或任何目标和之间的所有元素delegateTarget
)代表团目标选择匹配。
让我们把复杂一点:
<div id="parent">
<span>1</span>
<span>2 <b>another nested element inside span</b></span>
<p>paragraph won't fire delegated handler</p>
</div>
基本逻辑如下:
//attach handler to an ancestor
document.getElementById('parent').addEventListener('click', function(e) {
//filter out the event target
if (e.target.tagName.toLowerCase() === 'span') {
console.log('span inside parent clicked');
}
});
虽然当上述不匹配event.target
嵌套的过滤器内。 我们需要一些迭代逻辑:
document.getElementById('parent').addEventListener('click', function(e) {
var failsFilter = true,
el = e.target;
while (el !== this && (failsFilter = el.tagName.toLowerCase() !== 'span') && (el = el.parentNode));
if (!failsFilter) {
console.log('span inside parent clicked');
}
});
小提琴
编辑:更新的代码为jQuery的仅匹配后代元素.on
做。
注意:这些片段是为了便于说明,在现实世界中不能使用。 除非你不打算支持旧IE,当然。 对于老的IE,你需要拥有对测试addEventListener
/ attachEvent
以及event.target || event.srcElement
event.target || event.srcElement
,可能还有一些其他的怪癖,如检查事件对象是否被传递到处理函数或可在全球范围内。 值得庆幸的是jQuery也都可以无缝地在后台为我们后面。 =]
Necromancing:
万一有人需要上/生活与香草的JavaScript来取代JQuery的:
打字稿:
/// attach an event handler, now or in the future,
/// for all elements which match childselector,
/// within the child tree of the element maching parentSelector.
export function subscribeEvent(parentSelector: string | Element
, eventName: string
, childSelector: string
, eventCallback)
{
if (parentSelector == null)
throw new ReferenceError("Parameter parentSelector is NULL");
if (childSelector == null)
throw new ReferenceError("Parameter childSelector is NULL");
// nodeToObserve: the node that will be observed for mutations
let nodeToObserve: Element = <Element>parentSelector;
if (typeof (parentSelector) === 'string')
nodeToObserve = document.querySelector(<string>parentSelector);
let eligibleChildren: NodeListOf<Element> = nodeToObserve.querySelectorAll(childSelector);
for (let i = 0; i < eligibleChildren.length; ++i)
{
eligibleChildren[i].addEventListener(eventName, eventCallback, false);
} // Next i
// https://stackoverflow.com/questions/2712136/how-do-i-make-this-loop-all-children-recursively
function allDescendants(node: Node)
{
if (node == null)
return;
for (let i = 0; i < node.childNodes.length; i++)
{
let child = node.childNodes[i];
allDescendants(child);
} // Next i
// IE 11 Polyfill
if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.msMatchesSelector;
if ((<Element>node).matches)
{
if ((<Element>node).matches(childSelector))
{
// console.log("match");
node.addEventListener(eventName, eventCallback, false);
} // End if ((<Element>node).matches(childSelector))
// else console.log("no match");
} // End if ((<Element>node).matches)
// else console.log("no matchfunction");
} // End Function allDescendants
// Callback function to execute when mutations are observed
let callback:MutationCallback = function (mutationsList: MutationRecord[], observer: MutationObserver)
{
for (let mutation of mutationsList)
{
// console.log("mutation.type", mutation.type);
// console.log("mutation", mutation);
if (mutation.type == 'childList')
{
for (let i = 0; i < mutation.addedNodes.length; ++i)
{
let thisNode: Node = mutation.addedNodes[i];
allDescendants(thisNode);
} // Next i
} // End if (mutation.type == 'childList')
// else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
} // Next mutation
}; // End Function callback
// Options for the observer (which mutations to observe)
let config = { attributes: false, childList: true, subtree: true };
// Create an observer instance linked to the callback function
let observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(nodeToObserve, config);
} // End Function subscribeEvent
JavaScript的:
/// attach an event handler, now or in the future,
/// for all elements which match childselector,
/// within the child tree of the element maching parentSelector.
function subscribeEvent(parentSelector, eventName, childSelector, eventCallback) {
if (parentSelector == null)
throw new ReferenceError("Parameter parentSelector is NULL");
if (childSelector == null)
throw new ReferenceError("Parameter childSelector is NULL");
// nodeToObserve: the node that will be observed for mutations
var nodeToObserve = parentSelector;
if (typeof (parentSelector) === 'string')
nodeToObserve = document.querySelector(parentSelector);
var eligibleChildren = nodeToObserve.querySelectorAll(childSelector);
for (var i = 0; i < eligibleChildren.length; ++i) {
eligibleChildren[i].addEventListener(eventName, eventCallback, false);
} // Next i
// https://stackoverflow.com/questions/2712136/how-do-i-make-this-loop-all-children-recursively
function allDescendants(node) {
if (node == null)
return;
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
allDescendants(child);
} // Next i
// IE 11 Polyfill
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.msMatchesSelector;
if (node.matches) {
if (node.matches(childSelector)) {
// console.log("match");
node.addEventListener(eventName, eventCallback, false);
} // End if ((<Element>node).matches(childSelector))
// else console.log("no match");
} // End if ((<Element>node).matches)
// else console.log("no matchfunction");
} // End Function allDescendants
// Callback function to execute when mutations are observed
var callback = function (mutationsList, observer) {
for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
var mutation = mutationsList_1[_i];
// console.log("mutation.type", mutation.type);
// console.log("mutation", mutation);
if (mutation.type == 'childList') {
for (var i = 0; i < mutation.addedNodes.length; ++i) {
var thisNode = mutation.addedNodes[i];
allDescendants(thisNode);
} // Next i
} // End if (mutation.type == 'childList')
// else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
} // Next mutation
}; // End Function callback
// Options for the observer (which mutations to observe)
var config = { attributes: false, childList: true, subtree: true };
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(nodeToObserve, config);
} // End Function subscribeEvent