开发者

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 some开发者_开发技巧thing 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


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' })


$.extend({
  myPlugin : function( parameters, callbackFn ){

   ...do what needs to be done...

    if( $.isFunction( callbackFn ) ){
      callbackFn.call( someArguments);
    }

  }

});

$.myPlugin( { param1: 'sdfsdf' }, function(args){
 ..here's your callback...
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜