在jQuery插件中编写回调函数

时间:2010-05-28 10:22:37

标签: jquery jquery-callback

我正在编写一个jQuery插件,所以我可以在很多地方重用这个代码,因为它是一个非常好用的代码片段,代码本身为一个已经从隐藏行克隆的表添加了一个新行,它继续对新行执行大量操作。

我目前正在引用它:

$(".abc .grid").grid();

但是我想要包含一个回调,因此调用插件的每个区域都可以在添加行时做一些更独特的事情。我之前使用过jQuery AJAX插件,因此使用了success回调函数,但无法理解代码在后台如何工作。这就是我想要实现的目标:

$(".abc .grid").grid({
    row_added: function() {
        // do something a bit more specific here
    }
});

这是我的插件代码

(function($){           

    $.fn.extend({ 

        //pass the options variable to the function
        grid: function() {

            return this.each(function() {

                grid_table=$(this).find('.grid-table > tbody');
                grid_hidden_row=$(this).find('.grid-hidden-row');
                //console.debug(grid_hidden_row);
                $(this).find('.grid-add-row').click(function(event) {
                /* 
                 * clone row takes a hidden dummy row, clones it and appends a unique row 
                 * identifier to the id. Clone maintains our jQuery binds
                 */

                    // get the last id
                    last_row=$(grid_table).find('tr:last').attr('id');
                    if(last_row===undefined) {
                        new_row=1;
                    } else {
                        new_row=parseInt(last_row.replace('row',''),10)+1;
                    }

                    // append element to target, changes it's id and shows it
                    $(grid_table).append($(grid_hidden_row).clone(true).attr('id','row'+new_row).removeClass('grid-hidden-row').show());

                    // append unique row identifier on id and name attribute of seledct, input and a
                    $('#row'+new_row).find('select, input, a').each(function(id) {
                        $(this).appendAttr('id','_row'+new_row);
                        $(this).replaceAttr('name','_REPLACE_',new_row);
                    });

                    // disable all the readonly_if_lines options if this is the first row
                    if(new_row==1) {
                        $('.readonly_if_lines :not(:selected)').attr('disabled','disabled');
                    }
                });

                $(this).find('.grid-remove-row').click(function(event) {
                /* 
                 * Remove row does what it says on the tin, as well as a few other house 
                 * keeping bits and pieces
                 */

                    // remove the parent tr
                    $(this).parents('tr').remove();

                    // recalculate the order value5
                    //calcTotal('.net_value ','#gridform','#gridform_total');

                    // if we've removed the last row remove readonly locks
                    row_count=grid_table.find('tr').size();
                    console.info(row_count);
                    if(row_count===0) {
                        $('.readonly_if_lines :disabled').removeAttr('disabled');
                    }

                });

            });

        }

    });

})(jQuery);

我已经完成了对elgooG的通常搜索...但是我似乎得到了很多噪音而且收效甚微,非常感谢任何帮助。

谢谢!

2 个答案:

答案 0 :(得分:9)

也许是这样的?

$.fn.extend({ 

    //pass the options variable to the function
    grid: function(callbacks) {

        // The following can be used so you don't need
        // to test for callback existence in the rest 
        // of the plugin
        var defaults = {
            before: function() {},
            after: function() {},
            row_added: function() {}                
        }
        callbacks = $.extend({},defaults,callbacks);

        // perform callback
        if (callbacks.before)
            callbacks.before();

        return this.each(function() {
            // do stuff
            if (callbacks.row_added)
                callbacks.row_added();
            // do more stuff
        }

        // perform callback
        if (callbacks.after)
            callbacks.after();
   }
});

用这样的话来称呼它:

$("#grid").grid({
    before: function() {},
    after: function() {},
    row_added: function() {}
});                                                              

编辑:我刚刚添加了默认回调,因此您无需测试是否存在回调。就个人而言,我喜欢在调用之前测试存在,但你可能更喜欢这条路线。

答案 1 :(得分:2)

你可以阅读这篇文章:

http://www.learningjquery.com/2009/03/making-a-jquery-plugin-truly-customizable

其中包含一个关于提供回调功能的段落......

var defaults = {

    onImageShow : function(){}, // we define an empty anonymous function
                                // so that we don't need to check its
                                // existence before calling it.
    // ... rest of settings ...
};

// Later on in the plugin:     
$nextButton.bind('click', showNextImage);

function showNextImage() {
    // DO stuff to show the image here...
    // ...
    // Here's the callback:
    settings.onImageShow.call(this);
}