不引人注意的Javascript模糊事件处理 [英] Unobtrusive Javascript Obfuscates Event Handling

查看:150
本文介绍了不引人注意的Javascript模糊事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你知道我最喜欢obtrusive javascript吗?你总是知道当你触发事件时要做什么。

 < a onclick =thisHappens()/> 

现在每个人都喝着不引人注目的助手,这不是很明显。调用绑定事件可能发生在您的页面上包含的任何数量的javascript文件的任何行上。如果您是唯一的开发人员,或者如果您的团队有一些常规使用某种格式的CSS类的绑定事件处理程序,那么这可能不是问题。在现实世界中,它使得很难理解你的代码。



像Firebug这样的DOM浏览器似乎可以帮助,但是浏览所有的元素的事件处理程序属性只是为了找到一个执行你正在寻找的代码。即使这样,它通常只是告诉你这是一个没有行号的匿名函数()。



我发现在发现事件被触发时执行什么JS代码的技术是使用Safari的分析工具,它可以告诉你在一段时间内JS被执行的时间,但是有时候可以通过很多JS进行搜索。



得到一个更快的方式来了解当我点击一个元素时发生了什么。有人可以启发我吗?

解决方案

如果您使用jQuery可以利用其高级事件系统并检查功能附加事件处理程序的主体:

  $('body')。click(function(){alert('test')} )

var foo = $('body')。data('events');
//您可以查询$ .data(object,'events')并返回一个对象,然后查看附加到哪些事件。

$ .each(foo.click,function(i,o){
alert(i)//事件的guid
alert(o)//函数定义的事件处理程序
});

或者你可以实现自己的事件系统。


You know what I liked best about obtrusive javascript? You always knew what it was going to do when you triggered an event.

<a onclick="thisHappens()" />

Now that everybody's drinking the unobtrusive kool-aid it's not so obvious. Calls to bind events can happen on any line of any number of javascript file that get included on your page. This might not be a problem if you're the only developer, or if your team has some kind of convention for binding eventhandlers like always using a certain format of CSS class. In the real world though, it makes it hard to understand your code.

DOM browsers like Firebug seem like they could help, but it's still time consuming to browse all of an element's event handler properties just to find one that executes the code you're looking for. Even then it usually just tells you it's an anonymous function() with no line number.

The technique I've found for discovering what JS code gets executed when events are triggered is to use Safari's Profiling tool which can tell you what JS gets executed in a certain period of time, but that can sometimes be a lot of JS to hunt through.

There's got to be a faster way to find out what's happening when I click an element. Can someone please enlighten me?

解决方案

If you're using jQuery you can take advantage of its advanced event system and inspect the function bodies of event handlers attached:

$('body').click(function(){ alert('test' )})

var foo = $('body').data('events');
// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.

$.each( foo.click, function(i,o) {
    alert(i) // guid of the event
    alert(o) // the function definition of the event handler
});

Or you could implement your own event system.

这篇关于不引人注意的Javascript模糊事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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