1

私は初めての jQuery プラグインを作成していますが、いくつかのスピード バンプに遭遇しました。基本的に、プラグインの呼び出し元に実行してもらいたいことは次のとおりですが、プラグインを構成する方法がわかりません。

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

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

したがって、基本的に「dataloader」の値は必須で、中括弧内のオプションはオプションの設定であり、buildComplete は何かが完了したときに実行される関数です。

「buildComplete」関数 (など) をプラグイン呼び出し元に実装する方法がわかりません。「buildComplete」は、使用されるページごとに異なるため、以下に示す方法は避けたいと思います。

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

これで何かを見つけることができる基本的な例はありますか?

ありがとう、spryno724

4

2 に答える 2

0
$.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...
});
于 2011-03-18T00:02:15.070 に答える
0

これで始められるはずです

(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' })
于 2011-03-17T23:54:14.523 に答える