mootools_在MooTools中实现类似jQuery的事件语法

mootools

If you take a peek inside the MooTools core Element/Events source code, you'll see the following collection of events:

如果您浏览MooTools核心的Element / Events源代码,就会看到以下事件集合:


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
};


As you probably know, in order to add an event, you need to code something similar to:

您可能知道,为了添加事件,您需要编写类似于以下内容的代码:


	$('element').addEvent('click',function(e) {
		//do stuff
	});


In jQuery you code something like:

在jQuery中,您可以编写以下代码:


	$('#element').click(function(e) {
		//do stuff
	});


I don't prefer that syntax but if you're a Moo developer and you wanted to implement jQuery-like syntax for all events or you're slowly making your way from jQuery to MooTools, you can use the event collection cited above and the snippet to follow to quickly make that possible.

我不喜欢这种语法,但是如果您是Moo开发人员,并且想为所有事件实现类似jQuery的语法,或者您正在慢慢地从jQuery过渡到MooTools,则可以使用上面引用的事件集合和遵循以下摘要以快速实现这一目标。


//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);


Here's a few examples of using the newly implemented methods:

以下是一些使用新实现的方法的示例:


/* 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);
	});
});


Like I said, I don't find this syntax appealing, but I wanted to show how easy it is to do.

就像我说的那样,我觉得这种语法并不吸引人,但是我想展示它是多么容易。

翻译自: https://davidwalsh.name/implement-jquery-mootools-event

mootools

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值