2

私は次の機能を考えています:

$('.aclass').MyPluginInit()
$('.aclass').SomeMethodOfMine()

しかし、どのようにして1行目から2行目に移動するのでしょうか。理想的な世界では、2行目で生成された例外をトラップし(存在しないメソッドを呼び出そうとした場合)、オブジェクトのセットをループして、$('.aclass')それぞれについてプロパティを確認できます(たとえば、$this)は、上記のメソッドを含み、への呼び出しによってそこに配置されました.MyPluginInit()。次に、メソッドを呼び出します。

問題は、例外をトラップして、それが発生したオブジェクトに戻る方法を見つけることができないことです。のハンドラーはwindow.onerror、例外を生成したURLと行番号を教えてくれますが、それをオブジェクトに関連付けることはできません。

死者(またはこの場合は生まれていない人)の育てを他にどのように達成できるかについての考えはありますか?

  • ekkis

ps AutovivificationとJavascriptを読みましたが、私が求めているのは少し異なります。

4

2 に答える 2

0
// define your initializer
function MyPluginInit () {
  var e;
  for (e in this) {

    // give this object the method
    this[e].SomeMethodOfMine = function () {
      console.log("Wee!");
    }
  }
}

// call init using the array-ish thing returned by jQuery as `this`
MyPluginInit.call($(".aclass"));

// to call the method, you need to refer to an *element* in the array
// this is because we only gave the method to the elements, not to the array itself
$(".aclass")[0].SomeMethodOfMine();

これを行う優れた方法は思いつきませんでしたが、このコードは機能的であり、奇妙なグローバル例外処理を必要としません。または、配列の要素のプロトタイプを変更することを検討しましたか? 次に、要素が「初期化」されていない場合にどのように動作するかを決定するために、メソッドにいくつかのロジックを含めるだけで済みます。

通常はSomeMethodOfMinejQuery が返すオブジェクトのプロトタイプに追加することをお勧めしますが、それは であることが判明したためObject、おそらく得策ではありません。

于 2012-05-13T23:12:02.310 に答える
0

これが私が思いついたものです:それを使用するプラグインを含める前に、含めるライブラリに次の関数を入れてください:

function PluginMaker() {
    var plugin = url2fn($('script:last').attr('src'));
    $.fn[plugin] = function (opts) {
        opts = $.extend(true, {}, $[plugin], opts);
        for (fn in opts.fx) this[fn] = fxmk(fn);    // auto-vivification of methods
        this.each(function () { if (!this['$' + plugin]) this['$' + plugin] = opts; });
        opts.init(opts);  // plugin initialisation
        this.init(opts);  // per-object initialisation
        return this;
    };
    function fxmk(nm) {
        return function () {
            var args = arguments;
            this.each(function () {
                this['$' + plugin].fx[nm].apply(this, args);
            });
            return this;
        };
    }
    return plugin;
}

次に、次のようにプラグインを定義します。

// -- myplugin.js ---------------------------------------------------------------

(function ($) {
    $[PluginMaker()] = {
        // whatever state data you want to keep for your plugin
        fx: {
            MyMethod1: function () { /* within these methods */ },
            MyMethod2: function (msg) { /* this refers to the HTML element */ },
            // whatever other methods you want to define
            init: function (opts) {
                // used for per-element initialisation
            }
        },
        init: function(opts) {
            // used for plugin initialisation (one time)
        }
    };
});    

次に、実行できるプラグインを含めました。

$('.class').MyPlugin({ /* whatever options */ });
$('.class').MyMethod1();

あるいは:

$('#someId').MyMethod2();
于 2012-05-24T17:02:53.147 に答える