javascript - 创建一个 jQuery 插件 : best practices regarding functions' visibility?

标签 javascript jquery jquery-plugins

我正在创建一个 jQuery 插件。到目前为止它工作正常,但我对我做事的方式有疑问:

jQuery.fn.myMethod = function() {
  return this.each(function(){
    MyScope.doSomething(jQuery(this).attr("id"));
  });
};

var MyScope = {

  // The functions contained in MyScope are extremely linked to the logic 
  // of this plugin and it wouldn't make a lot of sense to extract them

  doSomething: function(id){
    // something
    doSomethingElse(23);
    // some more code
    doSomethingElse(55);
  },

  doSomethingElse: function(someInt){
    // some code 
  }
};

我使用 MyScope 来存储我所有的“私有(private)”函数。我不希望用户能够使用 $("p").doSomething(),但我确实需要使用它们。

我可以移动 myMethod 函数中的所有内容,但它会创建一个 100 行长的函数,人们会因此讨厌我。

在这种情况下,最佳做法是什么?有没有关于这方面的优秀教程?

最佳答案

你可以封装你的函数来做你想做的事,像这样:

jQuery.fn.myMethod = function() {
  return this.each(function(){
    doSomething(jQuery(this).attr("id"));
  });        
  function doSomething(id){
    //do something
  }
  function doSomethingElse(){
    // some code
  }
};

You can view a quick demo here

“我可以移动 myMethod 函数中的所有内容,但它会创建一个 100 行长的函数,人们会因此讨厌我。” ....为什么?

代码必须在某处定义,如果您不希望它可以从外部访问,有几种方法,但我不明白为什么有人会不喜欢您这样做。一切都与范围和您想要的东西有关,只要您不多次声明它并只公开您想要的东西,我看不出有任何问题。

声明它的方式有多种,有些具有相同的效果,我给出的选项只是其中之一,但是将内容放在 myMethod 中是一种非常合理的方法。


为了更完整,here's another alternative :

(function($) { 
    function doSomething(id){
      //do something, e.g:  doSomethingElse('bob');
    }
    function doSomethingElse(str){
      //some code
    }
    $.fn.myMethod = function() {
      return this.each(function(){
        doSomething(jQuery(this).attr("id"));
      });   
    };
})(jQuery);

another :

(function($) { 
    var me = {
        doSomething: function(id){
         //do something, e.g:  this.doSomethingElse('bob');
        },
        doSomethingElse: function(str){
          //some code
        }
    };
    $.fn.myMethod = function() {
      return this.each(function(){
        me.doSomething(jQuery(this).attr("id"));
      });   
    };
})(jQuery);

相关文章:

关于javascript - 创建一个 jQuery 插件 : best practices regarding functions' visibility?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3014926/

相关文章:

javascript - 在 MVC 中使用单选按钮显示动态字段

javascript - 有没有办法将按钮 ID onClick 发送到引导模式?

javascript - 将不同列表中的两个可排序对象按其类别移动到相同位置

javascript - 如何在javascript中的2个模式之间拆分字符串

javascript - 在 FullPage.js 应用程序内滚动

javascript parseFloat '500,000' 在我需要 500000 时返回 500

javascript - 向下滚动时,粘性子 div 会更改其宽度

jquery - 将焦点集中到 jQueryUI 对话框中的第一个表单元素

jquery - 使用 jquery 自动完成插件与 Rails 的示例

javascript - $(...).modal 不是函数 jquery.min.js