在MooTools中实现类似于jQuery事件一样的语法 »
如果你查看过MooTools核心元素事件的源代码(Element.Event.js),您会看到下面的事件收集:
1 2 3 4 5 6 7 8 9 | Element.NativeEvents = { click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons mousewheel: 2, DOMMouseScroll: 2, //mouse wheel mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement keydown: 2, keypress: 2, keyup: 2, //keyboard focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window error: 1, abort: 1, scroll: 1 //misc }; |
我在《MooTools中的事件(上)》中具体的介绍了这些事件,并且进行了具体的分类和解释。
正如你知道的,以下是添加一个事件的具体语法,你需要的代码类似于:
1 2 3 | $('element').addEvent('click',function(e) { //单击以后产生了动作。。。。 }); |
在jQuery中的事件用法类似于:
1 2 3 | $('#element').click(function(e) { //单击以后产生了动作。。。。 }); |
如果您习惯了jQuery的语法格式,不想使用MooTools那样的事件添加方式,我想还是有办法的,我们可以使用上面的事件收集和稍微处理引用一下,马上就成为可能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //hash the element.natives so we can do stuff with it var hash = new Hash(Element.NativeEvents); //remove items that need to be replaced, add their replacements hash.erase('mouseover').erase('mouseout').erase('DOMMouseScroll'); hash.include('mouseenter',1).include('mouseleave',1); //initialize this var eventHash = new Hash({}); //for every event type, add to our hash hash.getKeys().each(function(event){ eventHash[event] = function(fn) { this.addEvent(event,fn); return this; } }); //make it happen Element.implement(eventHash); |
下面是使用新实施方法的几个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /* examples */ window.addEvent('domready',function() { $$('a').click(function(e) { e.stop(); alert('mouse click'); }); $$('a').contextmenu(function(e) { e.stop(); alert('right click'); }); $('myInput').keypress(function(e) { alert('key pressed: ' + e.key); }); }); |
太好了,MooTools是灵活的。。。