2

我正在考虑以下功能:

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

但是我们如何从第一行到第二行呢?在理想的世界中,我将能够捕获第 2 行中生成的异常(当我尝试调用一个不存在的方法时),循环遍历$('.aclass')表示的对象集,并为每个对象查看一个属性(说, $this) 包含所述方法并通过调用.MyPluginInit(). 然后我会调用该方法。

问题是我无法捕获异常并找到返回引发异常的对象的方法。的处理程序window.onerror将告诉我产生异常的 url 和行号,但我无法将其绑定到对象。

关于我如何才能实现死者复活(或在这种情况下从未出生)的任何想法?

  • 埃基斯

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();

我想不出一个很好的方法来做到这一点,但这段代码是功能性的,不需要任何奇怪的全局异常处理。或者,您是否考虑过修改数组元素的原型?然后你只需要在你的方法中包含一些逻辑来确定在元素没有被“初始化”的情况下如何行动。

通常我会建议添加SomeMethodOfMine到 jQuery 返回的对象的原型,但结果是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 回答