8

ok am kinda new to plugins i have used many in my projects, i have also written basic plugins that just work on elements with options:

(function($){
    $.fn.pulse = function(options) {
        // Merge passed options with defaults
        var opts = jQuery.extend({}, jQuery.fn.pulse.defaults, options);
        return this.each(function() {
            obj = $(this);             
            for(var i = 0;i<opts.pulses;i++) {
                obj.fadeTo(opts.speed,opts.fadeLow).fadeTo(opts.speed,opts.fadeHigh);
            };
            // Reset to normal
            obj.fadeTo(opts.speed,1);
        });
    };
    // Pulse plugin default options
    jQuery.fn.pulse.defaults = {
        speed: "slow",
        pulses: 2,
        fadeLow: 0.2,
        fadeHigh: 1
    };
})(jQuery); 

the above works ok, but obviously it performs one task, ideally i would like to be able to perform multiple tasks within a plugin so i could use:

$('#div').myplugin.doThis(options);
$('#div').myplugin.doThat(options;

reason being i have quite a large script which does various ajax calls to save data and query data from a database (using an external php file) I'd like to intergrate all this functionality into a plugin, but i don't know the best structure to use for it, ive looked at so many tutorials and have basically fried my brain, and i am confused as to how i should go about doing this.

is it just a question of creating a new function like:

$.fn.pluginname.dothis = function(options){
        return this.each(function() {
            //execute code
        };
   };

any pointers on this, or a template to get me started would be really helpful.

forever in need of help!!!


next problem:

(function($){
// Can use $ without fear of conflicts
    //var gmap3plugin = $.fn.gmap3plugin;
    var obj = this; // "this" is the jQuery object

    var methods = {
        init : function(options){
            var lat = $.fn.gmap3plugin.defaults[lat];
            var lng = $.fn.gmap3plugin.defaults[lng];
            alert('init'+' lat:'+lat+' --- lng:'+lng);
        },
        show : function( ) {  },
        hide : function( ) { },
        update : function( content ) { }
    };



    $.fn.gmap3plugin = function(method){
        // Method calling logic
        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.tooltip' );
        };
    };
    $.fn.gmap3plugin.defaults = {
        mapdiv :'#mapdiv',
        region : 'uk',
        lat : 53.4807125,
        lng : -2.2343765
    };
})(jQuery);

this is functioning and gets the right function that is passed, but how do i access the values in the $.fn.gmap3plugin.defaults the code in my init method returns undefined for lat and lng

init : function(options){
    var lat = $.fn.gmap3plugin.defaults[lat];
    var lng = $.fn.gmap3plugin.defaults[lng];
    alert('init'+' lat:'+lat+' --- lng:'+lng);
},

or can i not access thhe data in $.fn.gmap3plugin.defaults from a function???

2 Answers 2

10

If you look at the design of some of the other jQuery plugins and jQuery UI, what they do is they have a single function $('#div').myplugin({options}), and then they can do different functions by passing a string instead of an object $('#div').myplugin('performdifferenttask') which can in turn call a helper function that is hidden from the user.

For an example look at http://jqueryui.com/demos/progressbar/#methods

Here is an example that will hopefully alleviate your confusion:

(function($) {
    $.fn.myplugin = function(options) {
        if(options == 'function1')
            function1();
        else if(options == 'function2')
            function2();
        else {
            //do default action
        }
    }

    function function1() {
        //do something
    }

    function function2() {
        //do something else
    }
}

Then in use:

$.myplugin({option1: 4, option2: 6}); //does default behavior
$.myplugin('function1'); //calls function1()
$.myplugin('function2'); //calls function2()
Sign up to request clarification or add additional context in comments.

4 Comments

hmm ok, i think jqueryui plugin architecture mentions something abpout that, i did have a read but it just left me in a state of confusion!! any good tutorial you could point me towards?
thanks samuel i will have a go and see where i get, it certainly looks to makew more sense than other articles i have read.
I cannot seem to get a working implementation of your given example. I keep receiving an "Uncaught SyntaxError: Unexpected identifier" on line "$.myplugin('function1');"
I know this was a while ago, but @Chris you probably get an error because the code has syntax mistakes. $.fn.myplugin = ... needs a closing semi-colon and the end of the code snippets misses )(jQuery);
10

Following Samuel's answer, you can also use the following to avoid double handling the function names:

(function($) {
    $.fn.myplugin = function(options, param) {
        if( typeof(this[options]) === 'function' ) {
            this[options](param);
        }
        // do default action

        this.function1 = function() {
            //do something
        }

        this.function2 = function(param) {
            //do something else (with a parameter)
        }
    }    
}

The addition of the param variable allows you to call functions like below:

$.myplugin(); // does default behaviour
$.myplugin('function1'); // run function 1
$.myplugin('function2'); // run function 2
$.myplugin('function2',{ option1 : 4, option2 : 6 }); // run function 2 with a parameter object

See http://jsfiddle.net/tonytlwu/ke41mccd/ for a demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.