YUI事件体系之Y.Do
Contents
YUI团队在种种场合不断的夸耀自己的事件体系是多么强大:
- YUI 3′s Event module is one of the strengths of the library –Eric Miraglia, YUI Theater — Luke Smith: “Events Evolved”
- YUI 3 is not all about DOM manipulation — it also contains a robust set of class/object management tools, not to mention our powerful custom events –Tilo Mitra, 10 Things I Learned While Interning at YUI
- One of the strengths of the YUI App Framework is that it’s integrated tightly with the rest of YUI and benefits from YUI’s fantastic event system and plugin/extension infrastructure. –Ryan Grove, How can I decided whether to choose YUI 3’s MVC or Backbone for a new project?
事实的确如此吗?就使用YUI的开发者反馈来看,应该是不错的:
- AFAIK YUI 3’s event system is the most sophisticated of any JavaScript framework. Am I wrong in thinking that? –Walter Rumsby
- I love the event system in YUI. Pure awesomeness. –Kevin Isom
- I am constantly impressed by the degree of excellence I find in working with the YUI3 framework –Andrew Wooldridge, Cross YUI Communication and Custom Events
作为一名YUI用户,我对其事件体系的强大深有体会。从本篇文章起,我将对YUI事件机制做一个全面分析。
本次我们介绍的是比较基础的两个对象Y.EventHandle和Y.Do。千里之行积于跬步,YUI整套事件机制也是从这两个对象开始构筑的。
Y.EventHandle
Y.EventHandle的作用很简单:注销事件/消息监听。
1 | Y.EventHandle = function (evt, sub) { |
Y.Do
Y.Do的作用是:向对象方法前面或者后面插入其它方法(前置、后置方法),以达到动态修改对象行为的目的。这种方式,也称作AOP。
示例
让我们先来看个简单的例子:
1 | // 例1 |
在不修改原对象方法的基础上,可以方便的添加前置、后置方法,并且注销这些方法也很容易。Y.Do非常漂亮的解决了我们动态修改对象方法的需求!很难想象,如果不用Y.Do代码会复杂成怎样。
源代码分析
接下来,让我们看看YUI的内部实现吧。这是多么有趣的事,就像小时候买把手枪,想不明白为什么可以射击,就砸开一看究竟。
为了更容易的看懂代码的核心,我做了适当的简化,感兴趣的朋友可以去看未删节的源码。
1 | // 代码版本为YUI3.4.1,YUI3.5.0对Y.Do的实现有所改进 |
适用场景
a) 动态修改对象方法
请参照例1。
b) 动态修改原型方法
原型也是对象,所以,另外一个适用场景就是修改原型方法。
1 | // 例2 |
c) 动态修改宿主方法
为宿主对象添加插件时,插件往往需要在宿主一些方法前后执行某些操作。YUI提供了一个很好的例子。
d) 动态修改被扩展对象方法
为对象添加扩展时,扩展对象往往需要在被扩展对象一些方法前后执行某些操作。YUI提供了一个很好的例子。
进阶使用
由于简化代码,省略了一些细节。Y.Do还有很多功能,例如:可以根据前置方法返回值阻止默认方法执行、替换参数等等。下面介绍一些这样的进阶使用方式:
1 | // 例3 |