简体   繁体   English

重写jQuery插件方法

[英]Override jQuery plugin methods

I've taken a stab on creating a jQuery plugin used to delete records. 我曾尝试创建一个用于删除记录的jQuery插件。 It will first warn the enduser of the record to be deleted, and then delete the record from the database and remove the row from the page. 它将首先警告最终用户要删除的记录,然后从数据库中删除该记录并从页面中删除该行。

The method that removes the row from the page is complete() . 从页面中删除行的方法是complete() Typically, I will need to remove rows from the page one of several ways, or maybe even redirect to another page. 通常,我将需要使用以下几种方法之一从页面中删除行,甚至可能重定向到另一页面。 As such, I want to configure the plugin to use one of several of these ways, and if one doesn't exist, then be able to totally override the complete() method. 因此,我想将插件配置为使用以下几种方法之一,如果不存在,则可以完全覆盖complete()方法。

My plan was to have the default complete() method just call another function (ie deleteMainRow() ), and upon configuration, I would just change the function to be executed (ie deleteChildRow() ). 我的计划是让默认的complete()方法仅调用另一个函数(即deleteMainRow() ),并且在配置后,我将更改要执行的函数(即deleteChildRow() )。

When attempting to do so, however, I get an error TypeError: this.deleteChildRow is not a function . 但是,尝试这样做时,出现错误TypeError: this.deleteChildRow is not a function

How can this be done? 如何才能做到这一点?

PS. PS。 While not my question and while a response is desired but not expected, I am confused on how to access properties and methods within the plugin. 虽然不是我的问题,并且希望得到响应,但是却没有期望,但我对如何访问插件中的属性和方法感到困惑。 As seen by my script, I sometimes access them as this.someProperty and other times as settings.someProperty . 从我的脚本可以看出,有时我以this.someProperty访问它们,而其他时候以settings.someProperty访问它们。 Also, to make things work, I needed to define 'elem' and 'dialog' as a global variable which I am not sure is correct. 另外,为了使事情正常进行,我需要将“ elem”和“ dialog”定义为一个不确定的全局变量。 Any advise would be appreciated. 任何建议将不胜感激。

Thank you 谢谢

$(function() {

    $("#main_list tbody img.deleteListRecord").deleteRecord({
        serverGetRecord:'getDelete_account',
        serverDeleteRecord:'delete_account',
        getMessage  :function (data) {
            return '<p class="dialog-question">ARE YOU SURE YOU WANT TO DELETE THIS ACCOUNT?</p><h1 class="dialog-name">'+data.name+'</h1><p class="dialog-delete">'+h(data.address)+'</p><p class="dialog-location">'+h(data.location)+'</p>';
        },
        complete:function(){console.log(this);this.deleteChildRow();}
    });

});

(function($){
    //Used to delete records.  Will first warn enduser of the record to be deleted, and then delete the record from the database and remove the row from the page.
    var defaults = {
        //Server accessed using index.php?cid=123&controller=someController&task=someTask
        'url'               :'index.php',
        'cid'               :ayb.component.id,  //Default component ID for given page
        'controller'        :ayb.component.controller, //Default controller ID for given page
        'CSRF'              :ayb.CSRF,//CSRF to send to server for all POSTs
        'serverGetRecord'   :'getRecord', //Server method to get record data
        'serverDeleteRecord':'deleteRecord',//Server method to delete record data
        'getID'             :function () {  //Return ID of record.  User can override if different that this 
            return $(elem).parent().parent().data('id'); 
        },
        'complete'          :function () {  //User can select one of the pre-defined routines or completely override 
            deleteMainRow(); 
        },
        'userComplete'      :function () {},  //Any extra user-defined methods to call when complete 
        'buildMessage'      :function () {  //Create warning message.  Override if user doesn't want to get data from server.
            var t=this;
            $.get(this.url,{cid:this.cid,controller:this.controller,task:this.serverGetRecord,id:this.getID()},function (data){
                dialog.html((data.status==1)?t.getMessage(data):'Error getting delete information.');
                },'json'); 
        },
        'getMessage'        :function (data) {  //Get warning message.  User can override just getMessage and still use buildMessage 
            return '<p class="dialog-question">ARE YOU SURE YOU WANT TO DELETE THIS RECORD?</p>';
        }
    };

    //A couple of pre-defined delete completion routines
    var deleteMainRow=function(){
        $(elem).parent().parent().remove();
    }
    var deleteChildRow=function(){
        alert('deleteChildRow.');
    }
    var dialog; //Should I define this variable here?
    var elem; //Should I define this variable here?

    var methods = {
        init : function (options) {
            var settings = $.extend(defaults, options  || {});
            dialog=$('<div class="dialog-delete" title=""></div>')
            .appendTo('body')
            .dialog({
                autoOpen    : false,
                resizable   : false,
                height      : 300,
                width       : 440, 
                modal       : true,
                dialogClass : 'hide-title-bar',
                open: function(event, ui){settings.buildMessage()},
                buttons: [{
                    text    : 'YES, DELETE IT',
                    "class" : 'red',
                    click   : function() {
                        dialog.dialog('close');
                        $.post(this.url,{cid:settings.cid,controller:settings.controller,task:settings.serverDeleteRecord,CSRF:settings.CSRF,id:settings.getID()},function (status){
                            if(status==1){
                                settings.complete();
                                settings.userComplete();
                            }
                            else{alert('Error deleting record');}
                        });
                    }
                    },
                    {
                        text     : 'CANCEL',
                        "class"  : 'gray',
                        click    : function() {$(this).dialog("close");}
                    }
                ]
            });
            return this.each(function () {
                $(this).click(function(e) {
                    elem=this;
                    dialog.dialog('open');
                });
            });
        },
        destroy : function () {
            //Anything else I should do here?
            delete dialog;
            return this.each(function () {});
        }
    };

    $.fn.deleteRecord = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.deleteRecord');
        }    
    };
    }(jQuery)
);

Put this: 把这个:

$(function() {

    $("#main_list tbody img.deleteListRecord").deleteRecord({
        serverGetRecord:'getDelete_account',
        serverDeleteRecord:'delete_account',
        getMessage  :function (data) {
            return '<p class="dialog-question">ARE YOU SURE YOU WANT TO DELETE THIS ACCOUNT?</p><h1 class="dialog-name">'+data.name+'</h1><p class="dialog-delete">'+h(data.address)+'</p><p class="dialog-location">'+h(data.location)+'</p>';
        },
        complete:function(){console.log(this);this.deleteChildRow();}
    });

});

After your module is declared and called :) 声明并调用模块后:)

Because you are calling anonymously what wasn't even created yet :) 因为您正在匿名呼叫,甚至还没有创建:)

  • Create a closure and save original plugin to future reuse; 创建一个闭包并保存原始插件以备将来使用;
  • Recreate the plugin with the same name; 用相同的名称重新创建插件;
  • Do all what you want and call original plugin. 做所有您想做的事,并调用原始插件。

     (function(){ var originalPlugin = $.fn.pluginname; $.fn.pluginname = function(options) { var defaults = { someOption: 'string', anotherOption: { /* some object, if you need it ... */ }, overridedfunction: function() { /* something */ } } var options = $.extend(defaults, options); var $this = $(this); $this.css('background-color', 'red'); // for example /* do something with '$this' applying any jquery */ originalPlugin.apply(this, arguments); } })(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM