开发者

Writing a better jQuery plugin

开发者 https://www.devze.com 2022-12-21 07:13 出处:网络
at the moment I have my jQuery plugin running it\'s logic in if statments. For example I have: (function($) {

at the moment I have my jQuery plugin running it's logic in 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 abo开发者_StackOverflow中文版ut 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. 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.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号