jQuery自製Plugin-Bind事件函式時檢查有沒有Bind過

  • 10840
  • 0
  • Web
  • 2010-12-16

因為寫一個豐富Ajax的網站,JavaScript一定會寫很多,有時莫明奇妙的一個HtmlElement Bind二個事件函式以上,可以照成click一次,卻Post二次以上,原因是不同的地方呼叫初始化的函式,所以我就自己寫了一個Plugin去避免這個問題。

因為寫一個豐富Ajax的網站,JavaScript一定會寫很多,有時莫明奇妙的一個HtmlElement Bind二個事件函式以上,可能照成click一次,卻Post二次以上,原因是不同的地方呼叫初始化的函式,所以我就自己寫了一個Plugin去避免這個問題。

 

(function ($) {
    //jquery object擴展
    $.extend($.fn, {
        BindCheck: function (id, type, callback) {
            ///檢查有沒有重覆的id,沒有才Bind,如果沒有給id,就判斷有沒有重覆的type

            if (arguments.length == 2) {
                callback = type;
                type = id;

                //沒有id,只判斷有沒有bind
                $.each(this, function (index, elem) {
                    $elem = $(elem);
                    if (!($elem.data("events") && $elem.data("events")[type])) {
                        $elem.bind(type, callback);
                    }
                });

            } else {
                //有id
                $.each(this, function (index, elem) {
                    $elem = $(elem);
                    var bindCheck = $elem.data("BindCheck");
                    if (!bindCheck) {
                        bindCheck = {};
                        $elem.data("BindCheck", bindCheck);
                    }

                    if (!bindCheck[id]) {
                        $elem.bind(type, callback);
                        bindCheck[id] = true;
                    }
                });
            }
        }
    });
})(jQuery)

 

範例

HTML:

<input id="test1" type='button' value="test 1"/>
<input id="test2" type='button' value="test 2"/>

 

JS:

$(function(){
    $("#test1").BindCheck("click",function(){ alert(1)});    
    $("#test1").BindCheck("click",function(){ alert(2)}); 
    $("#test1").BindCheck("click",function(){ alert(3)});
    
    $("#test2").BindCheck("test2-1","click",function(){ alert(1)});    
    $("#test2").BindCheck("test2-1","click",function(){ alert(2)}); 
    $("#test2").BindCheck("test2-2","click",function(){ alert(3)}); 
    $("#test2").BindCheck("test2-2","click",function(){ alert(4)}); 
})

 

說明

 

2-5是設定test1的click 事件函式,以type做區隔,一個type只會Bind一次,所以按下test1,只會 alert(1)

6-9是設定test2的click 事件函式,以id做區隔,一個id只會Bind一次,所以按下test2, 會alert(1)、alert(3)