Search code examples
jqueryjquery-pluginsmethodsjquery-callback

jQuery Method in Plugin Caller


I am writing my first jQuery plugin and I ran into a few speed bumps. Here is what I would like my plugin caller to do, basically, but I'm not sure how to structure the plugin:

$('div.selector').myPlugin(
    'dataloader', {
    { 
        source : 'source.json',
        autoUpdate : true
    },

    buildComplete : function() {
        //Do something when the building is completed
    }
});

So, basically, the "dataloader" value is required, the options inside of the curly braces are optional settings, and the buildComplete is a function which is executed once something has been completed.

I'm not sure how to implement a "buildComplete" function (or the like) into the plugin caller. I would like to avoid the way shown below, since "buildComplete" would be different for each page it is used:

//No can do!
$('div.selector').myPlugin('dataloader').buildComplete('do something');

Is there a basic example where I could find something on this?

Thanks, spryno724


Solution

  • This should get you started

    (function($){ // avoid variable polution by wrapping like this
        $.fn.myPlugin = function(dataloader,options_in){
                options = $.extend({},{ // create option object by extending empty array with default values and then overwriting with passed options
                    buildComplete: $.noop // default value for buildComplete is empty function
                },options_in)
    
                if(condition == met){ // in certain circumstance
                    options.buildComplete() // run the buildComplete function
                }
    
            }
    })(jQuery)
    
    // call like this
    $('div.delector').myPlugin('dataloader',{ buildComplete: function(){ alert('the build is complete') }, otherOption: 'whatever' })