开发者

How to write a callback handler function in jQuery plugin

I'm writing a jQuery plug-in to handle a callback function after an event is fired.

(function($){
    return $.fn.myPlugin = function (options) {
         var defaults = {
             callback:defaultCallback,
             many_more_params:'default etc',
             many_more_params2:'default etc',
             etc:'default etc'
         }
         var settings = $.extend(defaults, options);

         var defaultCallback = function (params) {
             // do default actions with params
         }

         $(this).click (function () {
             var params = { param1:'hello', param2:'goodbye'};
             settings.callback(params);
         });
    };
})(jQuery);

In the page I would like to set a custom callback like this

function customCallback (params) {
    // do custom actions with params
}

var opt = {
    callback:customCallback,
    many_more_params:'etc',
    many_more_params2:'etc',
    etc:etc
}
$('#id').myPlugin(opt);

How can I let the callb开发者_运维百科ack function work properly?


Change the order of your code. Put:

var defaultCallback = function (params) {
             // do default actions with params
}

before

var defaults = {
     callback:defaultCallback,
     many_more_params:'default etc',
     many_more_params2:'default etc',
     etc:'default etc'
 }

and it should work they way you want it to.

Example: http://jsfiddle.net/niklasvh/k5Wvb/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜