2011-08-24 50 views
4

我一直試圖抓住我的想法來構造一個插件,以便它可以接受帶有選項的方法調用,只需方法調用,init上的選項和不帶選項的init。JQuery插件結構。使用選項,方法和選項的方法

到目前爲止,這裏是我的。

(function($) { 
    var settings = {}; 
    var defaults = { 
     args : "default args" 
    }; 
    var methods = { 
     init : function(options) { 
      if(options) { 
       settings = $.extend({},defaults,options); 
      } 
     }, 
     test : function(arg) { 
      alert("test: " + arg.args); 
      alert("args: " + settings.args); 
     } 
    }; 
    $.fn.dataTable = function(method) { 
     var args = arguments; 
     var $this = this; 
     return this.each(function() { 
      if (methods[method]) { 
       return methods[method].apply($this, Array.prototype.slice.call(args, 1)); 
      } else if (typeof method === 'object' || ! method) { 
       return methods.init.apply($this, args); 
      } else { 
       $.error('Method ' + method + ' does not exist on jQuery.plugin'); 
      } 
     }); 
    }; 

})(jQuery); 


$(document).ready(function(){ 
    $(".tbl").dataTable(); 
    //$(".tbl").dataTable({ args : "hello world" }); 
    $(".tbl").dataTable("test",{args:"test args passed"}); 
    //$(".tbl").dataTable("test"); 
}); 

但是這個我收到

測試:通過

ARGS測試ARGS:未定義

有什麼幫助?

回答

3
(function($) { 
    var defaults = { 
     string1 : "hello ", 
     string2 : "world!" 
    }; 
    var methods = { 
     init : function(options) { 
      if(options) { 
       $.extend(defaults,options); 
      } 
      alert(defaults.string1 + defaults.string2); 
     }, 
     test : function(arg) { 
      alert("test: " + arg.args); 
      alert("args: " + defaults.string1 + defaults.string2); 
     } 
    }; 
    $.fn.dataTable = function(method) { 
     var args = arguments; 
     var $this = this; 
     return this.each(function() { 
      if (methods[method]) { 
       return methods[method].apply($this, Array.prototype.slice.call(args, 1)); 
      } else if (typeof method === 'object' || ! method) { 
       return methods.init.apply($this, Array.prototype.slice.call(args, 0)); 
      } else { 
       $.error('Method ' + method + ' does not exist on jQuery.plugin'); 
      } 
     }); 
    }; 

})(jQuery); 


$(document).ready(function(){ 
    $(".tbl").dataTable(); 
    //$(".tbl").dataTable({ string1 : "foo", string2 : "bar" }); 
    $(".tbl").dataTable("test",{args:"test args passed"}); 
    //$(".tbl").dataTable("test"); 
}); 
+1

我唯一的擔心是,如果我嘗試在一個頁面上初始化插件的兩個實例,會產生複雜情況。 'var $ this = this' – rlemon

+1

我知道這是一箇舊帖子,但是謝謝!另外,re:你的註釋,而不是'.apply($ this ...)',使用'.apply($(this)...)'至少使用'.each()'函數中的單個元素。 – Scrimothy

+0

是的,該行必須讀取:'return methods [method] .apply($(this),Array.prototype.slice.call(outerArguments,1));'在每個循環的特定元素處應用函數,否則爲'$ this'爲8個匹配div的數組的例子會導致函數調用64次(8個循環x每個循環8個元素)。在默認的'init'部分也是一樣。這意味着'$ this'分配是不需要的並且可以被刪除。 - 我已經命名爲'outerArguments'而不是'args',使它成爲乾淨的代碼,但這對'$(this)'問題無關緊要。 –

相關問題