JQuery - 将GUI对象连接到事件的最佳方式? [英] JQuery - Best way of wiring GUI objects to events?

查看:80
本文介绍了JQuery - 将GUI对象连接到事件的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从几年前JQuery出现以来,我一直在我所有的客户端脚本中使用它。最初我使用'$()语法来抓取和操作对象,对我而言,这是将按钮事件明确地连接到函数的'旧skool'范式:

 < button onClick ='myFunction(this);'... /> 

附带相关功能:

<$ p $
alert {'这是像我这样的老年人做的!')
}
函数myFunction(obj){
alert



我的一些同事喜欢将脚本附加到JQuery事件中:



<$ p (
函数(事件){
alert('这是最新的JQuery的做事方式');
}
);
);

最初,我发现过于繁琐的JQuery语法依赖于匿名函数等难以阅读,但我的眼睛和大脑已经调整好了,所以我现在对任何一种方式都很满意。然而,我会希望我们的代码商店保持一致。有人对哪种方法更好有任何意见吗?

解决方案

我认为第二种方法比较干净有几个原因:


  • 它确实允许您分离内容和行为,也就是说您可以先定义内容的结构,然后再处理具体行为......如果你的团队涉及不同的技术配置文件(有人照顾原始HTML,其他人是Javascript专家......),那么它特别有用。


  • strong>有助于维护,正如您知道在哪里寻找那样可能会出现错误的javascript,而不必查看整个HTML。


  • 如果您的HTML实际上是动态的(在服务器端生成的,PHP或ASP.NET),实际上很难将这些客户端元素包含在HTML中生成...这是一个非常常见的错误来源,因此它是很好的JavaScript的方式。



Ever since JQuery came along a few years ago I've been using it in all my client-side scripts. Initially I used the '$() syntax to grab and manipulate objects this, to me, is the 'old skool' paradigm of explicitly wiring up button events to functions:

<button onClick='myFunction(this);' ...  />

with a related function:

function myFunction(obj){
    alert('this is how old-timers like me do it!')
}

Some of my colleagues prefer to do the attaching of scripts to events a la JQuery:

$(document).ready(
    $("#myButton").click(
        function(event){
            alert('this is the newer JQuery way of doing things');
        }
    );
);

Initially I found the overly-bracey JQuery syntax with its reliance on anonymous functions etc. difficult to read, but my eyes and brain have adjusted so I'm happy with either way now. I would however like our codeshop to be consistent. Does anyone have any opinions on which approach is 'better'?

解决方案

I think the second approach is cleaner for several reasons :

  • it really allows you to separate content and behaviour, that is you can define your content's structure first and only later take care of the specific behaviour... This is especially helpful if your team involves different technical profiles (somebody takes care of the raw HTML, somebody else is the Javascript expert ...)

  • This really helps maintenance, as you know where to look for the potentially buggy javascript if something goes wrong , instead of having to look through the whole HTML.

  • when your HTML is actually dynamic (generated on server-side, à la PHP or ASP.NET), it is actually quite painful to have to include those client-side elements in the HTML you generate... This is a very common source of errors, therefore it is good to have the javascript out of the way.

这篇关于JQuery - 将GUI对象连接到事件的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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