I am trying to write a jQuery plugin. For simplicity let's say that my code is
$.fn.myplugin = function() {
return this.each(function() {
$('a.mypluginToken').live('click', function(){})
}
}
As per above code every single time $('a').myplugin is called, a binding is done for 'click' event because of 'live'. I need that binding to b开发者_JS百科e done only once and not for each element that invokes my plugin.
one solution is that after binding the click event I set a data on document saying 'binding_done'. And check for that data every single time. Even though that solution will work I am wondering if there is a better jQuery design pattern that I am missing.
Thanks.
I am using jQuery 1.4.2
If I understand your code correctly, when you call $('a').myplugin
, you want all $('a.mypluginToken')
to have the click function? Because that doesn't really make any sense.
First, when you do $('a.mypluginToken').live
you are saying that any time an <a>
with class mypluginToken
is added, add a click event. So there's no need to keep calling this plugin. If you just want to bind a click event just do .bind('click', function() {})
. Or you can just call $('a.mypluginToken').live
once when the page loads and forget about it.
Secondly, why are you looping through each element of the selector if the body is just selects all the things you want anyway?
If you want that piece to work, you can do $('a.mypluginToken').unbind().bind('click', function() {})
. This will make sure that every time you bind, there are no events attached already. However, this code will remove ALL events currently bound, even the non click ones.
Are trying to only attach the click even to class mypluginToken
within the currently selector? Then you want
function click_event() {};
$.fn.myplugin(function() {
$(this).filter('.mypluginToken').unbind('click', click_event).bind('click', click_event);
}
Pulling your click even function out of the call and referencing it makes sure that unbind will only unbind that function and not all click events.
Have you looked at jQuery's built-in .one() method? I'm not sure if it'll fit exactly into your application, but essentially it's an event handler that will only fire once per element.
精彩评论