---
title: "YUI 3 学习笔记（3）- Event"
author: "yiyu"
date: "2010-03-03T16:02:46Z"
tags: ["HTML", "JavaScript", "YUI", "jQuery", "浏览器"]
categories: ["Web前端"]
slug: "yui-3-3-event"
draft: false
lastmod: "2010-04-05T13:37:54Z"
id: 607022
url: "https://yiyu.iteye.com/blog/607022"
---

YUI的Event包可以用来操纵DOM事件，也可以自定义事件。 \[b]1. 要使用Event，首先要引入YUI3的种子文件：\[/b] \[code="html"] \[/code] 然后加载相应模块： \[code="javascript"] YUI().use('event', function(Y) { }); \[/code] \[b]2. 设置事件响应函数:on()\[/b] 有两个on方法，一个是YUI的，一个是Node的 Y.on("click", handleClick, "#foo p") 设置元素"#foo p"的click事件处理函数为handleClick。 foo.on("click", handleClick) 的作用与上面的一样 对于YUI的on方法，参数如下： 1) 事件名。关于各事件在主要浏览器中的兼容性，可以参见这里： http://www.quirksmode.org/dom/events/index.html 2) 事件处理句柄 3) 元素，可以是多个，多个的写法是这样：\["#foo p", "#bar"] 4) 上下文对象，即事件处理函数中的this,如果忽略，就是target元素的Node 5) 参数，可以有多个，按顺序为事件处理函数中event之后的参数 \[b]3. 移除事件响应函数\[/b] 有三种方式： 1) 在事件名前加前缀，然后用YUI的detach移除 2) 保存事件句柄，然后通过该句柄移除 3) 用YUI的detach，指定事件名、处理函数和元素 \[code="javascript"] YUI().use('node-base', function(Y) { //an event handler: function handleClick(e) { Y.log(e); } var fooHandle = Y.on("eventcatgory|click", handleClick, "#foo"); //第一种 Y.detach('eventcategory|click'); Y.detach('eventcategory|\*'); //第二种 fooHandle.detach(); Y.detach(fooHandle); //第三种 Y.detach("click", handleClick, "#foo"); }); \[/code] 另外，Event.purgeElement可以清理所有通过on添加的事件处理函数，而且可以 设定是否对子元素递归清理。 \[b]4.模拟鼠标事件\[/b] 可以通过Node.simulate()模拟鼠标事件，可以模拟7种鼠标事件： * click * dblclick * mousedown * mouseup * mouseover * mouseout * mousemove 同时可以指定一些附加信息，例如： \[code="javascript"] YUI().use('node-event-simulate', function(Y) { Y.one("body").simulate("click", { shiftKey: true }); }); \[/code] 模拟按下Shift键的click事件，这些附加信息包括： * detail - click的次数. * screenX/screenY * clientX/clientY * ctrlKey/altKey/shiftKey/metaKey * button - 0：左，1：右, 2：中 * relatedTarget \[b]5. 模拟键盘事件\[/b] 可以模拟以下事件： * keyup * keydown * keypress keyup和keydown必须指定keyCode，keypress必须指定charCode，另外还可以 指定ctrlKey, altKey, shiftKey和metaKey，以下是几个例子： \[code="javascript"] YUI().use('node-event-simulate', function(Y) { var node = Y.one("#myDiv"); node.simulate("keydown", { keyCode: 97 }); //simulate typing "a" node.simulate("keypress", { charCode: 97, altKey: true }); }); \[/code] \[b]6. available(onAvailable)和contentready(onContentReady)事件\[/b] available事件在一个元素刚刚出现在DOM树中时触发。 contentready事件在一个元素和它的下一个元素都可以用getElementById获得 时触发，以保证该元素已加载完毕（除了动态加载的内容以外） \[b]7. domready(onDOMReady)事件\[/b] domready事件在DOM树构建完成时触发，有可能是在图像加载完毕以前。 \[b]8. delegate方法\[/b] 事件代理(Event delegate)机制可以在父元素处唯一绑定一个listener监听该 父元素的多个子元素处发生的事件，以如下的html为例： \[code="html"]

- *Item Type One*
- *Item Type Two*
- *Item Type Three*

\[/code] 以下这段代码将一listener绑定到"container"，却监听着其3个子元素(

)处的 click事件： \[code="javascript"] YUI().use("event-delegate", function(Y) { Y.delegate("click", function(e) { Y.log("Default scope: " + this.get("id")); Y.log("Clicked list item: " + e.currentTarget.get("id")); Y.log("Event target: " + e.target); Y.log("Delegation container: " + e.container.get("id")); }, "#container", "li"); }); \[/code] \[b]9. focus和blur事件\[/b] DOM的focus和blur事件是不做冒泡传递的，但YUI的Event utility的focus和blur事件 却可以，因此可以实现集中的事件处理。 以下是一段示例代码： \[code="javascript"] YUI().use("event-focus", function(Y) { var handle = Y.on("focus", function(e, arg1, arg2, etc) { Y.log("target: " + e.target + ", arguments: " + arg1 + ", " + arg2 + ", " + etc); }, "#toolbar", Y, "arg1", "arg2", "etc"); }); \[/code] 其中"#toolbar"是一个包含3个按钮的

，如下： \[code="html"]

\[/code] \[b]10. mouseenter和mouseleave事件\[/b] YUI也提供mouseenter和mouseleave事件，代码如下所示： \[code="javascript"] YUI().use("event-mouseenter", function(Y) { Y.on("mouseenter", function (e) { Y.log("Mouse entered: " + this.get("id")); }, "#container"); Y.on("mouseleave", function (e) { Y.log("Mouse left: " + this.get("id")); }, "#container"); }); \[/code] \[b]11. 自定义事件\[/b] 可以使用on实现简单的自定义事件。注册listener是这样的： \[code="javascript"] Y.on('customapp:started', function(arg1, arg2, arg3) { Y.log('Custom App Started, now I can do a a few things); }); \[/code] 激发这个事件是这样的： \[code="javascript"] YUI().use('event-custom', function(Y) { Y.fire('customapp:started', 1, 2, 3); }); \[/code] 另外可以用augment将一对象提升为Event target，用publish定义一个Event，注册listener 还是用on，激发事件还是用fire，下面是示例代码： \[code="javascript"] YUI().use('event-custom', function(Y) { function Publisher() { this.publish("publisher:testEvent", {}); } Y.augment(Publisher, Y.EventTarget, null, null, 'test'); publisher = new Publisher(); publisher.on("publisher:testEvent", function(e){ alert(e); }); publisher.fire("publisher:testEvent", 'test arg1'); }); \[/code] 其中publish只有当需要覆盖默认配置时才需要。