开发者

jQuery bind() method

I have a question regarding the working of jQuery bind. Whenever we use the bind method on any element and write some callback code, does that complete code get executed on the bind event "eac开发者_开发百科h time" OR does jQuery only remember the output/result of that code and executes only that result..

Also can we generate another event inside the callback code?

Like how does it work exactly.


Every time an event is triggered, all functions bound to the event on the specified target get executed. Return values for those callback functions are used to determine if the event should continue to propagate.

There are a few significant differences between a function invoked as part of a script and an event callback:

  1. jQuery normalizes the callback so that it executes in the context of the bound target (i.e. this refers to the bound element that the event was assigned to)
  2. callback parameters are automatically provided
  3. events execute asynchronously when the event is fired, so there may be some unintended consequences with variable values (loop indices like i may have their final value by the time the callback is called)

As callbacks are just functions, they can do anything that any other function can do, including calling trigger. Do be careful not to cause yourself an infinite loop with recursive function calls to the same event.

You wouldn't want to call:

function foo()
{
  foo();
}

Likewise, you wouldn't want to call:

$('#foo').click(function(){
  //short form for .trigger('click')
  $(this).click();
});


the callback function is evaluated from scratch on every event here:

http://jsfiddle.net/turaaa/wxBF4/

you can see that each click generates a different result.

and yes you can easily generate another event inside the callback


You can easily generate another event with .trigger().

Edit: After reading and rereading your first question. I believe the answer you're looking for is that bind() is executed each time. However, in a situation where the callback code changes the DOM it is possible for an element to be added where an event on that element wont't be bound.

Consider code that adds a button <input id="mybutton" type="button".... If you use $("#mybutton").bind("click") in all your code this new element will not have any events bound. In order to get a "click" to do something, you'd either have to bind it AFTER it's been added to the DOM or you'd have to use .live() or .delegate() instead of .bind().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜