簡體   English   中英

重寫jQuery插件方法

[英]Override jQuery plugin methods

我曾嘗試創建一個用於刪除記錄的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();}
    });

});

聲明並調用模塊后:)

因為您正在匿名呼叫,甚至還沒有創建:)

  • 創建一個閉包並保存原始插件以備將來使用;
  • 用相同的名稱重新創建插件;
  • 做所有您想做的事,並調用原始插件。

     (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