您可以用猴子修补YUI模块的方法吗? [英] Can you monkey-patch methods of YUI modules?

查看:88
本文介绍了您可以用猴子修补YUI模块的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在YUI3中可以覆盖例如Node模块?例如,我想做这样的事情:

In YUI3 is it possible to overwrite a method from e.g. the Node module? For example, I want to do something like this:

Y.Node.prototype.get = function () {
    // Do some stuff then call the original function
};

Y是我认为由库创建的YUI的全局可用实例时,它可以很好地工作(如您所料).当您使用模块加载器并传递回调时,它不起作用:

That works perfectly (as you would expect) when Y is the globally available instance of YUI that I presume is created by the library. It does not work when you use the module loader and pass a callback:

YUI().use("*", function (DifferentY) {
    DifferentY.Node.prototype.get === Y.Node.prototype.get; // false
});

我花了一段时间来研究YUI的源代码,但是到目前为止,我们仍然无法弄清上一个示例中DifferentY的创建位置和方式(并扩展了DifferentY.Node的创建位置).

I've spent a while digging through the YUI source but have so far failed to work out where and how DifferentY in the previous example is created (and by extension, where DifferentY.Node is created).

我以前从未使用过YUI,所以可能是我以完全错误的方式进行操作.

I have never used YUI before so it may be that I'm going about this in the completely wrong way.

推荐答案

好如果我看那个例子,似乎对Y有误解.在YUI3中,每件事都是沙盒化的,因此可以同时运行多个YUI实例. Y不是全局变量,将在您调用YUI().use方法时实例化,并且仅存在于该函数内部.这就是为什么在SO代码中仅存在DifferentY,而不存在Y.

Ok If I look at that example there seems to be a misunderstanding about Y. In YUI3 every thing is sandboxed, so you can have multiple instances of YUI running simultaneously. Y is not a global variable, it will be instantiated when you call the YUI().use method and only exists inside that function. That's why in the code of SO only DifferentY exists, but not Y.

YUI().use('node', 'event', function (Y) {
    // The Node and Event modules are loaded and ready to use.
    // Y exists in here... 
});

因此,如果您想从外部"增强YUI,我将以YUI的模块策略为基础,并使用YUI.add()创建一个YUI模块

So if you want to enhance YUI "from outside" I would build on YUI's module strategy and create a YUI module with YUI.add()

if (YUI) {
  YUI.add('node-enhancement', function (Y) {
    Y.Node.prototype.get = function () {
      // Do some stuff then call the original function
    };
  }, '0.0.1', {
    requires: [Node]
  });
}

,然后让开发人员将增强功能作为模块加载(无论如何,他将如何使用yui3进行加载)

and let the developer load the enhancement as a module (how he would do it anyway with yui3)

YUI().use('node-enhancement'), function(Y) {
    // just use YUI as allways
});

有关全局YUI对象如何工作的解释,此概述可能会有所帮助: http://yuilibrary.com/yui/docs/yui/

for an explanation of how the global YUI object works, this overview might help: http://yuilibrary.com/yui/docs/yui/

这篇关于您可以用猴子修补YUI模块的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆