简体   繁体   English

编写更好的jQuery插件

[英]Writing a better jQuery plugin

at the moment I have my jQuery plugin running it's logic in if statments. 目前我有我的jQuery插件运行它的逻辑在if statments。

For example I have: 例如,我有:

(function($) {
    $.fn.myplugin = function(action) {

        if(action == "foo"){

        }

        if(action == "bar"){

        }

        if(action == "grapefruits"){            

        }

    }
})(jQuery);

Is there a better way to go about this? 有没有更好的方法来解决这个问题?

Also the same with event handlers, can I declare them inside the plugin? 对于事件处理程序也一样,我可以在插件中声明它们吗?

You can store different functions in an object and use an indexer, like this: 您可以在对象中存储不同的函数并使用索引器,如下所示:

(function($) {
    var methods = {
        foo: function(action) { ... },
        bar: function(action, someParam) { ... },
        grapefruits: function(action, param1, param2) { ... },
        ...
    };

    $.fn.myplugin = function(action) {    
        methods[action].apply(this, arguments);
    }
})(jQuery);

There's no reason to check the action multiple times, is there? 没有理由多次检查动作,是吗? YOu may as well use else if.I don't like the syntax for switch personally, and prefer this style. 你也可以使用其他if.I不喜欢switch个人的语法,更喜欢这种风格。 You can do it like 你可以这样做

    if(action == "foo"){
    }
    else if(action == "bar"){
    }
    else if(action == "grapefruits"){            
    }
    else{
    //this is the default/unspecified case
    }

Another option is to store each as a name in an object. 另一种选择是将每个作为名称存储在对象中。 This is done in Python a lot too, for instance. 例如,这在Python中也是如此。

   var plugin_actions={
      'foo':function(){},
      'bar':function(){},
      'grapefruits':function(){}
       }
   plugin_actions[action]();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM