简体   繁体   English

jQuery - 一旦将事件绑定到多个元素,每个元素的新实例?

[英]jQuery - when binding event to multiple elements at once, new instance for each element?

I have 100 BUTTONS in my page ( each of them has class =' btn '). 我的页面中有100个按钮(每个按钮都有class =' btn ')。

Also I have a single button which prepare all the other 100 buttons. 另外我有一个单一的 按钮准备所有其他 100层的按钮。

<input type='button' onclick='bindTheClickevent()' />

when pressed, - he calles bindTheClickevent () - (which binds the click event to all 100 others). 当按下时, - 他调用bindTheClickevent () - (将click事件绑定到所有其他100个)。

In the Script Section i put : 在脚本部分,我把:

function bindTheClickevent ()
{
        $(".btn").bind('click',function () {
          $(this).css('color','red');
         });
}

Questions 问题

1 ) In memory , how many instances of the anonymous function are created ? 1 )在内存中created多少个anonymous function instances

2 )In memory , Does the bindTheClickevent () function will ever be free (GC) ? 2 )在内存中, bindTheClickevent ()函数是否be free (GC) - please notice that the Bind is called inside the bindTheClickevent function... - 请注意绑定是 bindTheClickevent函数中调用的...

3 ) When , eventually - the bindTheClickevent function will be free to GC ? 3什么时候 ,最终 - bindTheClickevent函数will be free to GC

Lets make a change 让我们做出改变

function bindTheClickevent ()
    {
            $(".btn").bind('click',function () {
              changeColor($(this));
             });
    }

function changeColor(obj)
{
 $(obj).css('color','red');
}

now - after the change 现在 - 改变之后

1 )Is there any difference if I Do that ? 1 )如果我这样做有什么不同吗?

2 ) In memory , how many instances of the anonymous function are created ? 2 )在内存中created多少个anonymous function instances

3 )Does the bindTheClickevent () function will ever be free (GC) ? 3bindTheClickevent ()函数是否be free (GC) - please notice that the Bind is called inside the bindTheClickevent function... - 请注意绑定是 bindTheClickevent函数中调用的...

It looks like only one instance of the function is created in both circumstances. 看起来在这两种情况下只创建了一个函数实例。 It appears as though References to the anonymous function are attached as the event handlers for each element. 看起来好像引用匿名函数作为每个元素的事件处理程序。

Example - Using a closure to show the sharing of scope between button event handlers. 示例 - 使用闭包显示按钮事件处理程序之间的范围共享。

Note that this can cause interesting behavior if you involve closures because all elements will share the same function (and closure scope). 请注意 ,如果涉及闭包,这可能会导致有趣的行为,因为所有元素将共享相同的函数(和闭包范围)。

And no, your declared functions will not be GC'd because of their global scope. 不,由于其全球范围,您声明的功能将不会被GC。

Additionally 另外

To attach them independently (not by reference), loop over the selected elements with .each() and attach the function individually. 要单独附加它们(不是通过引用),请使用.each()所选元素并.each()附加该函数。

Example

$('.btn').each(function() {
    $(this).bind('click',function() {
        // each '.btn' has it's own copy of
        // this anonymous function
    }
});

"1) In memory , how many instances of the anonymous function are created ?" “1)在内存中,创建了多少个匿名函数实例?”

Which anonymous function? 哪个匿名功能?

For the inline onclick , you get a function assigned to the onclick property of the element like this: 对于内联onclick ,您将获得一个分配给元素的onclick属性的函数,如下所示:

function(event) {

    bindTheClickevent();

}

... or similar depending on the implementation. ......或类似的,取决于实施。 That function will be free for GC when the element is dereferenced or the function is dereferenced from the onclick property. 当元素被取消引用或从onclick属性取消引用该函数时,该函数对于GC是免费的。

With respect to the jQuery code: 关于jQuery代码:

$(".btn").bind('click',function () {
    $(this).css('color','red');
});

...while the anonymous function is shared, what you don't see is that if the elements in question do not already have a jQuery handler bound, jQuery will internally create a unique function for each element. ...虽然匿名函数是共享的,但你看不到的是,如果有问题的元素还没有绑定jQuery处理程序,jQuery将在内部为每个元素创建一个唯一的函数。

That internal handler is what actually gets bound to the element, and when the element receives an event, that handler is invoked, analyzes the event, and invokes the handler you originally passed (if necessary). 该内部处理程序实际上是绑定到该元素的,并且当该元素接收到一个事件时,将调用该处理程序,分析该事件,并调用您最初传递的处理程序(如果需要)。

This means 100 jQuery bound elements equals 101 unique function instances . 这意味着100个jQuery绑定元素等于101个唯一函数实例

In order to make sure that any handlers bound using jQuery are GC'd, you need to make sure that you always use jQuery to remove DOM elements . 为了确保使用jQuery绑定的任何处理程序都是GC,您需要确保始终使用jQuery删除DOM元素 If you don't, all the data (including handlers) stored in jQuery.cache doesn't get cleaned up, and so they'll always be referenced via the global jQuery namespace. 如果不这样做,存储在jQuery.cache中的所有数据(包括处理程序)都不会被清除,因此它们将始终通过全局jQuery名称空间引用。


EDIT: 编辑:

Given that there are 100 elements that have the class btn , that don't have any handlers bound by jQuery, then this code: 鉴于有100元素具有类btn ,没有任何由jQuery绑定的处理程序,那么这段代码:

$(".btn").bind('click',function () {
    $(this).css('color','red');
});

...will create 101 unique Function instances. ...将创建101唯一的Function实例。

Why 101 ? 为何选择101

Well, what jQuery does is the first time you bind a handler to an element, it internally creates a unique generic handler for every element. 嗯,jQuery做的是第一次将处理程序绑定到元素时,它在内部为每个元素创建一个唯一的通用处理程序。 This is the handler that is actually invoked when an event occurs, and handles all event types. 这是在事件发生时实际调用的处理程序,它处理所有事件类型。

Your handler function is never actually bound to the element. 您的处理函数实际上从未绑定到该元素。

So that generic internal handler when invoked will analyze the event that took place, and see if any handlers have been associated with the given element using .bind() that match that event type. 因此,调用时通用内部处理程序将分析发生的事件,并查看是否已使用与该事件类型匹配的.bind()将任何处理程序与给定元素相关联。 If so, it calls the handler that passed. 如果是这样,它会调用传递的处理程序。

Now let's say you bind another handler: 现在让我们说你绑定另一个处理程序:

$(".btn").bind('mouseenter',function () {
    $(this).css('color','blue');
});

...since we're binding to the same elements, they already have the necessary internal handler and another does not need to be created. ...因为我们绑定到相同的元素,所以它们已经具有必要的内部处理程序,而另一个则不需要创建。 So all that happens is that the function you pass is referenced internally, and is invoked by the generic internal handler when needed. 所有发生的事情都是您传递的函数在内部引用,并在需要时由通用内部处理程序调用。

As such, given the code snippets above, there now exists 102 unique Function instances. 因此,鉴于上面的代码片段,现在存在102唯一的Function实例。

If you do something like these: 如果您执行以下操作:

for (someiterations)
{
    $(myobj).bind("click",function()
    {
        // ...bla...
    });
}

In this case you are creating a new function each iteration. 在这种情况下,您将在每次迭代时创建一个新函数。 In your function this is not happening because you are passing the function to a parameter, so there is a place which has stored it's reference (yea the function param) that will do something like this: 在你的函数中,这不会发生,因为你将函数传递给参数,所以有一个地方存储了它的引用 (是函数参数),它将执行以下操作:

for (iterations)
{
    myob.addEventHandler(event, funcref);
}

So should be ok, now: 所以应该没问题,现在:

  1. Don't think so, not sure of the syntax however. 不要这么认为,但不确定语法。
  2. 1 as I explained 1正如我解释的那样
  3. No because it's in the global scope and it's not assigned to an instance, you can think of it as a constant, not as a variable 不,因为它在全局范围内并且未分配给实例,您可以将其视为常量,而不是变量

Note: The anonymous function will not be released, it's referenced by the event handler. 注意:匿名函数不会被释放,它由事件处理程序引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jquery遍历元素并将事件绑定到每个元素上 - jquery iterating over elements and binding an event onto each element 一次绑定到多个元素上的事件时是否有任何性能提升? - Any performance gain when binding to event on multiple elements at once? jQuery类选择器事件绑定是否将eventHandler附加到每个实例? - Does jQuery class selector event binding attach eventHandler to each instance? 使用JQuery的.each和.on将事件处理程序绑定到元素 - Binding event handlers to elements using JQuery's .each and .on 使用on将jquery中动态生成的元素上的多个事件处理程序对绑定 - Binding multiple event handler pairs on dynamically generated elements in jquery with on 将多个tspan子元素附加到svg文本对象时,每次都需要一个新的子元素吗? - When appending multiple tspan child elements to an svg text object, is a new child element needed each time? 事件应用于多个元素时只触发一次 - Event is triggered only once when applied to multiple elements jQuery收集一组元素,解开每个元素,然后将所有元素包装到新元素中 - JQuery collect group of elements, unwrap each and then wrap all in new element jQuery click事件未绑定到元素 - jQuery click event not binding to element jQuery对于多个事件具有相同的功能,每个事件针对不同的元素吗? - jQuery same function for multiple events, each event targeting different elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM