jQuery global custom events and live() doesn't seem to work
I'm struggling to get to grips with jQuery live() when combined with global custom events.
I've jsfiddled (and simplified) an example from jQuery docs itself.
Using 开发者_如何学Gobind()
works:
Using live()
doesn't:
I understand there are differences in how live()
and bind()
work, and that with live()
events can be cancelled if another event in the tree returned false etc.
I've read as many blog posts as I can get my hands on, but nothing out there seems to explain a combination of live()
and global custom events.
I just cannot figure out why live()
won't work in this example!
Can anyone help explain this to me?
You will need to target the elements you want when you trigger the event.
so use
$('p').trigger('myCustomEvent');
example at http://jsfiddle.net/gaby/QJDdH/2/
Update
This seems to be a decision from the jQuery team..
quote from the source code of the trigger method github source
// Handle a global trigger
if (!elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
The only alternative i can think of (besides tinkering with the jQuery source) would be to do a
$('*').trigger('myCustomEvent');
but it seems like it could be expensive.. (again not global in the sense that non DOM bound events will not get triggered)..
I think you want to do the following which is registring the live click event with the name myCustomEvent.
$("button").bind("click.myCustomEvent", function(e, myName, myValue) {
$(this).siblings("p").text("I've changed!");
});
精彩评论