开发者

jQuery callbacks - short version

开发者 https://www.devze.com 2022-12-28 05:38 出处:网络
I\'ve dug the manual and tried extensivelly to drop the extra function(){...} call after the error and success to do it like mootools but to no good luck.

I've dug the manual and tried extensivelly to drop the extra function(){...} call after the error and success to do it like mootools but to no good luck.

Is there any way i can avoid the extra function in jQuery?

function doFileDe开发者_如何学Golete(ui) {
    $.ajax({
        error: function() { doFileDeleteAnimation(ui, false) },
        success: function() { doFileDeleteAnimation(ui, true) },
        url: '/url-to-delete-file'
    });
}

Thank you!


If you have no arguments in the function you would like to call, yes, you can just pass the name of the function as your parameter for your callback. However, if you have at least one argument, you must declare the function and pass the necessary data.

Read more in the jQuery documentation regarding callbacks.


You could also eliminate that outer function by using Function.prototype.bind (either the Prototype library version or the ECMAScript 5 native version if your browser supports it). For example:

function handler(myBoolean) {
  console.log(myBoolean); // will output true
}

$(function() {
  $('#test').click(handler.bind(this, true));
});

The first argument to bind is the context you want to execute the function within. Subsequent parameters are passed to the handler function. When jQuery executes handler as a callback, the function calls are curried and the parameters it passes will be tacked onto the ones you specified in your bind call. So, in my example handler would receive three parameters when you click on #test: the boolean you passed in, the event object, and the DOM element that was clicked.

jQuery has a rough equivalent of bind with its function $.proxy. By default, it doesn't allow you to curry functions like bind does, but someone wrote an extension to it that will give it that functionality.

In my opinion, bind is a better choice than $.proxy since it has cleaner syntax, doesn't require you to monkey patch jQuery, and will be supported natively by browsers once ECMAScript 5 is fully implemented.

0

精彩评论

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