1

私は次のように定義されたプラグインを持っています:

(function( $ ){
    var mymethods = {
        init: function(opts) {
            // do some wild awesome magic
            if (opts.drawtablefirst) $(this).drawtable(); // This doesn't actually work of course
        },

        drawtable: function() {
            $(this).empty().append($("<table>")); // Empty table, I know...
        }
    }

    // Trackman table
    $.fn.myplugin = function(method) {

        if (mymethods[method] ) {
            return mymethods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method ) {
            return mymethods.init.apply(this, arguments);
        }
    }
})( jQuery );

drawtableメソッドからメソッドを呼び出せるようにしたいのですinitが、その方法がうまくいきません。私は主に次のようにプラグインをインスタンス化します。

$("div#container").myplugin({drawtablefirst: true})

drawtablefirstしかし、次のように、渡して後で手動で呼び出したくない場合があります。

$("div#container").myplugin('drawtable')

これを設定しdrawtableてアクセス可能なプラグイン メソッドにする最善の方法は何initですか?

また、元の要素にdrawtableviaでアクセスして$(this)もうまくいかないようです。そこに適切なアプローチは何ですか?

ありがとう。

4

1 に答える 1

0

このソリューションはjQuery-ui1.7+.widget機能を使用しています。これは、無料で入手できるものへの優れたリンクです。

$.widget("notUi.myPlugin",{
 options:{
   drawtablefirst:true,
   //...any other opts you want
 },
 _create:function(){
  // do some wild awesome magic
  if (this.options.drawtablefirst){
   this.drawtable(); // This actually works now of course
  } 
 },
 //any function you do not put an underscore in front of can be called via .myPlugin("name", //args)
 drawtable: function() {
   this.element.empty().append($("<table>")); // Empty table, I know...
 }
});
于 2012-04-20T18:38:24.180 に答える