2012-05-13 73 views
2

我想的以下功能:方法自动激活

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

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

问题是我无法捕捉异常并找到回到它所在的对象的方式。 window.onerror的处理程序会告诉我产生该异常的网址和行号,但我无法将其绑定到对象。

关于我还能如何完成死亡的提升(或者在这种情况下从未出生)的任何想法?

  • ekkis

附:我的确读过Autovivification and Javascript,但我所要求的有点不同。

+1

很难理解你的意思。你可以编辑它,或绘制图表? –

回答

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(); 
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,所以它可能不是一个好主意。

+0

感谢您的回复。亚,不是那里...必须解除引用并不美观,不,将它添加到Object原型并不是一个好主意。我确实解决了它。将分开发布,因此我可以将其标记为答案 – ekkis