2012-03-29 71 views
0

如果我想在我正在製作的jQuery插件上有一個可公開訪問的函數,這是做這件事的正確方法嗎?jQuery插件創作範圍

(function($) { 
    $.fn.myPlug = function(options) { 
     // Do this... 
     this.hello = function() { 
      return 1; 
     }; 
    } 
})(jQuery); 

var foo = $("div").myPlug(); 

// then do this... 
foo.hello(); 
+0

我看不出有什麼不妥的地方。 – 2012-03-29 17:48:29

回答

1

您應該構建您的插件,以便方法名稱可以作爲參數傳遞給您的插件。這是推薦的jQuery plugin authoring guide

(function($) { 

    var methods = { 
     init: function(options) { 

     }, 
     hello: function() { 
      return 1; 
     } 
    }; 

    $.fn.myPlug = 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.myPlug'); 
     } 
    }; 

})(jQuery); 

的使用會去是這樣的:

$("div").myPlug({ ... }); 
$("div").myPlug("hello"); // returns 1 
+0

有什麼特別的原因,爲什麼這是更可取的?我看到文檔說這樣做,但我無法弄清楚爲什麼這是一個更好的方法來做到這一點...... – Ian 2012-03-29 18:18:52

+0

我認爲最重要的是它比使用多個名稱空間的一個插件更好。當你使用這個方法時,你只需要一個名字空間(「myPlug」)。也許我首先誤解了你的問題 - 雖然你的插件返回了一個你可以採取行動的對象嗎? – 2012-03-29 19:52:17

+0

那麼,在我的示例中,我在插件中創建了一個成員函數,並且從我所知道的情況來看,它在$ .fn中沒有使用多個名稱空間(右?)。我只是想確定這一點...因爲JS的範圍有時會讓我無法迴避。 – Ian 2012-03-30 12:56:53