javascript - 重写 jQuery 插件方法

标签 javascript jquery

我尝试创建一个用于删除记录的 jQuery 插件。它首先会警告最终用户要删除的记录,然后从数据库中删除该记录并从页面中删除该行。

从页面中删除行的方法是complete()。通常,我需要通过多种方式之一从页面中删除行,或者甚至可能重定向到另一个页面。因此,我想将插件配置为使用其中几种方法之一,如果其中一种方法不存在,则能够完全覆盖 complete() 方法。

我的计划是让默认的complete()方法只调用另一个函数(即deleteMainRow()),并且在配置时,我只需将该函数更改为被执行(即deleteChildRow())。

但是,当尝试这样做时,我收到错误TypeError: this.deleteChildRow is not a function

如何做到这一点?

PS。虽然不是我的问题,虽然需要但不期望得到答复,但我对如何访问插件内的属性和方法感到困惑。从我的脚本中可以看出,我有时以 this.someProperty 的形式访问它们,有时则以 settings.someProperty 的形式访问它们。另外,为了使事情正常工作,我需要将“elem”和“dialog”定义为全局变量,我不确定这是否正确。任何建议将不胜感激。

谢谢

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

最佳答案

把这个:

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

});

在声明并调用模块之后:)

因为您正在匿名调用尚未创建的内容:)

关于javascript - 重写 jQuery 插件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621006/

相关文章:

javascript - Nodejs 文件系统数组排序数字

javascript - createElement() 未显示在查看源代码中

javascript - 无法访问创建的工作簿的工作表

javascript - 按钮在注册表单中不起作用

javascript - 重绘/刷新/设置超时 - 数据 xmlhttp.responseText

javascript - Google 的 buckyball doodle 是如何实现的?

Javascript - 如何使用单击功能访问对象的属性

javascript - 我的网络应用程序的小部件

javascript - 如何使用 jquery 接受双引号值

asp.net-mvc - Asp.net Mvc jquery ajax?