在 jQuery 插件中编写回调函数

发布于 2024-09-03 07:12:11 字数 3185 浏览 2 评论 0原文

我正在编写一个 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 上进行搜索...但我似乎收到了很多噪音,但收效甚微,任何帮助将不胜感激。

谢谢!

I'm writing a jQuery plug-in so I can reuse this code in many places as it is a very well used piece of code, the code itself adds a new line to a table which has been cloned from a hidden row, it continues to perform a load of manipulations on the new row.

I'm currently referencing it like this:

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

But I want to include a callback so each area the plug-in is called from can do something a bit more unique when the row has been added. I've used the jQuery AJAX plug-in before, so have used the success callback function, but cannot understand how the code works in the background. Here's what I want to achieve:

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

Here's my plug-in code

(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);

I've done the usually searching on elgooG... but I seem to be getting a lot of noise with little result, any help would be greatly appreciated.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

羁〃客ぐ 2024-09-10 07:12:11

也许是这样的?

$.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() {}
});                                                              

编辑:我刚刚添加了默认回调,这样您就不需要测试回调是否存在。就我个人而言,我喜欢在致电他们之前测试是否存在,但您可能更喜欢这条路线。

Maybe something like this?

$.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();
   }
});

Call it with something like this:

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

EDIT: I just added default callbacks so that you don't need to test for the existence of the callbacks. Personally, I like to just test for existence before calling them, but you might prefer this route.

无畏 2024-09-10 07:12:11

你可以阅读这篇文章:

http://www. Learningjquery.com/2009/03/making-a-jquery-plugin-truly-customized

其中包含有关提供回调功能的段落...

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);
}

Yuo can read this post:

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

which contains a paragraph on providing callback capabilities...

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文