简体   繁体   中英

Writing a better jQuery plugin

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 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. 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]();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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