I have a project coming up to build an interface which allows a user to construct content with pre-defined templates and code snippets.
我有一个项目即将构建一个界面,允许用户使用预定义的模板和代码片段构建内容。
We've already decided to use the jQuery and jQuery UI frameworks to help us with the dragging/dropping/sorting parts. There also needs to be some edit-in-place, and I'm going to use contenteditable
combined with jQuery's CSS functions.
我们已经决定使用jQuery和jQuery UI框架来帮助我们处理拖放/排序部分。还需要进行一些编辑,我将使用contenteditable结合jQuery的CSS函数。
I already have quite a bit of experience with both frameworks (and love them), but my typical project so far has run to about 50 lines whereas this one will run to a lot more than that, using more of the functions and writing my own plugins.
我已经对这两个框架都有相当多的经验(并且喜欢它们),但到目前为止,我的典型项目已经运行到大约50行,而这个项目将运行到更多,使用更多的函数并编写自己的插件。
Before I start work on the project I'm wondering if there are any common pitfalls with jQuery - kind of like 'jQuery - the Bad Parts'. Are there functions that are just best avoided? Are there functions which need working around?
在我开始研究项目之前,我想知道jQuery是否存在任何常见的陷阱 - 有点像'jQuery - Bad Parts'。是否有最好的避免功能?是否有需要解决的功能?
I read this link but it's now 2 years old and a lot has changed in jQuery (and browsers) since then.
我读了这个链接,但它现在已经2年了,从那以后jQuery(和浏览器)发生了很多变化。
Any 'Use this framework instead' or 'Don't use a framework' answers will be ignored - I have to use jQuery. Any 'jQuery is rubbish' rants that don't provide solutions will also be ignored. Constructive comments only please. If I knew how to do better in JavaScript what jQuery does, I wouldn't be using jQuery.
任何“使用此框架代替”或“不使用框架”的答案都将被忽略 - 我必须使用jQuery。任何不提供解决方案的“jQuery是垃圾”咆哮也将被忽略。只有建设性意见。如果我知道如何在JavaScript中做得更好jQuery,我就不会使用jQuery。
7 个解决方案
#1
8
I'll answer half of your question. Here's a laundry list of pitfalls based on painful experience, not all of which I have solutions to.
我会回答你问题的一半。这是一个基于痛苦经历的陷阱清单,并非所有我都有解决方案。
- The temptation to make heavy use of long chains of selectors ("ul#leftnav li p a.current ") makes your code brittle. It may FEEL clever ("Hey, I'm teh CSS master!"), but it breaks easily when layout changes in any non-trivial way.
- Using the DOM as the database. It seems like a neat idea to use .data() to attach data to your DOM elements, to track your page state, and to link DOM elements together, but if you go overboard, you start to lose track of what's where.
- Putting way too much stuff in $(document).ready(). Once again, it's natural to initialize all your events and data here, but you soon run into organizational and ordering problems. Look into MVC-like solutions to keep things organized.
- Not quite cross-browser. Test in all targeted browsers early and often! jQuery, although a wonderful abstraction, is still a leaky one. Events and attributes don't always behave exactly the same in different JS engines.
大量使用长链选择器的诱惑(“ul#leftnav li p a.current”)会使你的代码变得脆弱。它可能很聪明(“嘿,我是CSS主人!”),但是当布局以任何非平凡的方式改变时,它很容易破裂。
使用DOM作为数据库。使用.data()将数据附加到DOM元素,跟踪页面状态以及将DOM元素链接在一起似乎是一个巧妙的想法,但是如果你过分了,你就会开始忘记在哪里。
在$(document).ready()中添加太多东西。再一次,在这里初始化所有事件和数据是很自然的,但很快就会遇到组织和排序问题。研究类似MVC的解决方案,以保持组织有序。
不完全跨浏览器。尽早经常在所有目标浏览器中进行测试! jQuery虽然是一个很棒的抽象,但仍然是一个漏洞。事件和属性在不同的JS引擎中的行为并不总是完全相同。
#2
5
Keep the glue minimal
Things I've done in jQuery that I've learned to avoid:
我在jQuery中所做的事情,我学会了避免:
- Overusing big, clever plugins. Keep it simple or keep it out.
- Big, complex files. Keep files small and descriptive.
- Polluting the global namespace. Use closures per file. Export into a namespace.
- Constructing markup with
$()
. Template using backbone / mustache to keep js clean. - Brittle CSS selectors. Select by ID where possible, using hierarchy causes problems.
过度使用大而聪明的插件。保持简单或保持它。
大而复杂的文件。保持文件小和描述性。
污染全局命名空间。使用每个文件的闭包。导出到命名空间。
用$()构造标记。使用骨干/小胡子的模板来保持js干净。
脆弱的CSS选择器。尽可能按ID选择,使用层次结构会导致问题。
Keep it maintainable
Things I've done in jQuery that I've learned to do every time:
我在jQuery中所做的事情,我每次都学会了这样做:
- Definitely make use of automated testing. Maintains code structure and peace of mind.
- Keep state information out of the DOM, in a model.
- Choose storing callback functions and referring to them by var name over crazy function nesting.
- Make use of a minimal framework to establish conventions early.
绝对可以使用自动化测试。保持代码结构,让您高枕无忧。
在模型中将状态信息保留在DOM之外。
选择存储回调函数并通过var name在疯狂函数嵌套中引用它们。
利用最小的框架尽早建立约定。
That last one is a must. There are countless ways of organising the JS side of a project. Choose something like ember.js to give you a set of conventions, then stick to them!
最后一个是必须的。有无数种方法来组织项目的JS方面。选择像ember.js这样的东西给你一套约定,然后坚持下去!
#3
4
One of the most important challenges, whether or not the project uses jQuery, is code organization.
无论项目是否使用jQuery,最重要的挑战之一是代码组织。
With jQuery, it's very easy to write code like this:
使用jQuery,编写如下代码非常容易:
$.get('/data', function (data) {
// process data, then
alertThing.fadeIn(function () {
// when the alert is visible, handle clicks
alertButton.click(function () {
// the user confirmed, so post
$.post('/data', function () {
// ... and on and on
});
});
});
});
You end up with long chains and/or deeply nested functions that are hard to read and debug. Using Deferred objects can help, but it would be better to split your app into loosely coupled components. You can even package reusable (presentation, DOM-related) code into plugins.
您最终会遇到难以阅读和调试的长链和/或深层嵌套函数。使用Deferred对象可以提供帮助,但最好将应用程序拆分为松散耦合的组件。您甚至可以将可重用(表示,DOM相关)代码打包到插件中。
jQuery's strength is cross-browser DOM manipulation; when it comes to organizing program / business logic, jQuery isn't the right tool. (Storing non-presentation data on the DOM is basically a crutch for this.)
jQuery的优势在于跨浏览器DOM操作;在组织程序/业务逻辑时,jQuery不是正确的工具。 (在DOM上存储非演示数据基本上是一个拐点。)
Frameworks like Backbone or JavaScriptMVC help by providing structure for your code. It's "yet another framework to learn" but without it you end up writing your own MVC-like code anyway.
Backbone或JavaScriptMVC等框架通过为代码提供结构来提供帮助。它是“另一个学习的框架”,但如果没有它,你最终还是会编写自己的MVC代码。
#4
1
One of the biggest pitfalls is IE6. I find myself constantly having to make work arounds to make the jqueryUI stuff work in IE6 and forget about trying to make it work in IE 5.5
IE6是最大的陷阱之一。我发现自己经常不得不努力使jqueryUI的东西在IE6中运行而忘记尝试使它在IE 5.5中工作
#5
1
Well I am a N00B but most of the problems I faced with Jquery' functions not working was in $("div > label") type of functions. Some times it would plain not work in IE( i guess 7) and I would have to explicitly specify it. Also the Document.Ready function wont work for me when i had loads of scripts loading in IE7. Overall Even though the above things might have been due to error on my part I find it best to avoid using ELE.children("#id")
instead prefer ELE.find(".class")
as this will give u a bit of flexibility over the layout and Because u will be doing loads of things on similiar elements(ex. copy multiple divs) My only suggestions would be to use Classes instead of IDs and use Find instead of Children. What i am trying to say here is if u use Find instead of children atleast u gain independence from change in layout of individual element as long as they are in distinct containers.(hope this is useful)
好吧,我是N00B,但我遇到的Jquery函数无法正常工作的大部分问题都是$(“div> label”)类型的函数。有时它在IE中根本不起作用(我猜7),我必须明确指定它。当我在IE7中加载大量脚本时,Document.Ready函数也不适用于我。总的来说尽管上面的事情可能是由于我的错误,我发现最好避免使用ELE.children(“#id”)而不是喜欢ELE.find(“。class”),因为这会给你一点灵活性在布局上,因为你将在类似的元素上做大量的事情(例如复制多个div)我唯一的建议是使用Classes而不是ID并使用Find而不是Children。我想在这里说的是,如果你使用Find而不是孩子,只要他们在不同的容器中就可以从单个元素的布局中获得独立。(希望这很有用)
#6
0
One bad-practice trap to avoid is doing lots of HTML generation from within your javascript. For example, I see stuff like this a lot:
要避免的一个不良做法陷阱是在javascript中进行大量的HTML生成。例如,我看到很多这样的东西:
$('<a href="'+url+'">'+text+'</a>').appendTo('#container');
Beware! 90% of the time this kind of code is generating similar markup to that which is already coming from the server. In other words, as soon as the markup for your links change you'll to have to hunt down the line of javascript and update that as well.
谨防! 90%的情况下,这种代码生成的类似标记与已经来自服务器的代码相似。换句话说,只要链接的标记发生变化,您就必须追捕javascript行并更新它。
I highly recommend using the official jQuery templates plug-in as soon as you feel that first urge to generate HTML in your javascript!
我强烈建议您在首次尝试在javascript中生成HTML时,立即使用官方jQuery模板插件!
#7
0
I've personally worked a lot with jQuery and what I can say is the problems you will face are not with jQuery but with the nature of javascript itself. You need to keep your code organized and well documented. Try following some kind of mvc (backbonejs, javascript mvc or something of the kind). AVOID GLOBAL VARIABLES. Use namespaces for what ever objects you utilize. Use the document.ready for as few events as possible. Otherwise you are going to over pollut it and again... it becomes messy.
我个人使用jQuery工作了很多,我可以说你将遇到的问题不是jQuery,而是javascript本身的性质。您需要保持代码的组织和记录。尝试使用某种mvc(backbonejs,javascript mvc或类似的东西)。避免全球变量。使用命名空间来处理您使用的对象。尽可能少地使用document.ready。否则你会过度污染它再次......它会变得混乱。
Keep a javascript nature of things as in using closures, objects and methods.
保持事物的javascript性质,如使用闭包,对象和方法。
Careful of over appending strings into the dom. Make sure you are using .load() or .clone() to get html from your template file. If you use backbone or javascriptmvc this will come inherently.
小心地将字符串附加到dom中。确保使用.load()或.clone()从模板文件中获取html。如果你使用backbone或javascriptmvc,这将是固有的。
Hope this helps and good luck!
希望这有帮助,祝你好运!
#1
8
I'll answer half of your question. Here's a laundry list of pitfalls based on painful experience, not all of which I have solutions to.
我会回答你问题的一半。这是一个基于痛苦经历的陷阱清单,并非所有我都有解决方案。
- The temptation to make heavy use of long chains of selectors ("ul#leftnav li p a.current ") makes your code brittle. It may FEEL clever ("Hey, I'm teh CSS master!"), but it breaks easily when layout changes in any non-trivial way.
- Using the DOM as the database. It seems like a neat idea to use .data() to attach data to your DOM elements, to track your page state, and to link DOM elements together, but if you go overboard, you start to lose track of what's where.
- Putting way too much stuff in $(document).ready(). Once again, it's natural to initialize all your events and data here, but you soon run into organizational and ordering problems. Look into MVC-like solutions to keep things organized.
- Not quite cross-browser. Test in all targeted browsers early and often! jQuery, although a wonderful abstraction, is still a leaky one. Events and attributes don't always behave exactly the same in different JS engines.
大量使用长链选择器的诱惑(“ul#leftnav li p a.current”)会使你的代码变得脆弱。它可能很聪明(“嘿,我是CSS主人!”),但是当布局以任何非平凡的方式改变时,它很容易破裂。
使用DOM作为数据库。使用.data()将数据附加到DOM元素,跟踪页面状态以及将DOM元素链接在一起似乎是一个巧妙的想法,但是如果你过分了,你就会开始忘记在哪里。
在$(document).ready()中添加太多东西。再一次,在这里初始化所有事件和数据是很自然的,但很快就会遇到组织和排序问题。研究类似MVC的解决方案,以保持组织有序。
不完全跨浏览器。尽早经常在所有目标浏览器中进行测试! jQuery虽然是一个很棒的抽象,但仍然是一个漏洞。事件和属性在不同的JS引擎中的行为并不总是完全相同。
#2
5
Keep the glue minimal
Things I've done in jQuery that I've learned to avoid:
我在jQuery中所做的事情,我学会了避免:
- Overusing big, clever plugins. Keep it simple or keep it out.
- Big, complex files. Keep files small and descriptive.
- Polluting the global namespace. Use closures per file. Export into a namespace.
- Constructing markup with
$()
. Template using backbone / mustache to keep js clean. - Brittle CSS selectors. Select by ID where possible, using hierarchy causes problems.
过度使用大而聪明的插件。保持简单或保持它。
大而复杂的文件。保持文件小和描述性。
污染全局命名空间。使用每个文件的闭包。导出到命名空间。
用$()构造标记。使用骨干/小胡子的模板来保持js干净。
脆弱的CSS选择器。尽可能按ID选择,使用层次结构会导致问题。
Keep it maintainable
Things I've done in jQuery that I've learned to do every time:
我在jQuery中所做的事情,我每次都学会了这样做:
- Definitely make use of automated testing. Maintains code structure and peace of mind.
- Keep state information out of the DOM, in a model.
- Choose storing callback functions and referring to them by var name over crazy function nesting.
- Make use of a minimal framework to establish conventions early.
绝对可以使用自动化测试。保持代码结构,让您高枕无忧。
在模型中将状态信息保留在DOM之外。
选择存储回调函数并通过var name在疯狂函数嵌套中引用它们。
利用最小的框架尽早建立约定。
That last one is a must. There are countless ways of organising the JS side of a project. Choose something like ember.js to give you a set of conventions, then stick to them!
最后一个是必须的。有无数种方法来组织项目的JS方面。选择像ember.js这样的东西给你一套约定,然后坚持下去!
#3
4
One of the most important challenges, whether or not the project uses jQuery, is code organization.
无论项目是否使用jQuery,最重要的挑战之一是代码组织。
With jQuery, it's very easy to write code like this:
使用jQuery,编写如下代码非常容易:
$.get('/data', function (data) {
// process data, then
alertThing.fadeIn(function () {
// when the alert is visible, handle clicks
alertButton.click(function () {
// the user confirmed, so post
$.post('/data', function () {
// ... and on and on
});
});
});
});
You end up with long chains and/or deeply nested functions that are hard to read and debug. Using Deferred objects can help, but it would be better to split your app into loosely coupled components. You can even package reusable (presentation, DOM-related) code into plugins.
您最终会遇到难以阅读和调试的长链和/或深层嵌套函数。使用Deferred对象可以提供帮助,但最好将应用程序拆分为松散耦合的组件。您甚至可以将可重用(表示,DOM相关)代码打包到插件中。
jQuery's strength is cross-browser DOM manipulation; when it comes to organizing program / business logic, jQuery isn't the right tool. (Storing non-presentation data on the DOM is basically a crutch for this.)
jQuery的优势在于跨浏览器DOM操作;在组织程序/业务逻辑时,jQuery不是正确的工具。 (在DOM上存储非演示数据基本上是一个拐点。)
Frameworks like Backbone or JavaScriptMVC help by providing structure for your code. It's "yet another framework to learn" but without it you end up writing your own MVC-like code anyway.
Backbone或JavaScriptMVC等框架通过为代码提供结构来提供帮助。它是“另一个学习的框架”,但如果没有它,你最终还是会编写自己的MVC代码。
#4
1
One of the biggest pitfalls is IE6. I find myself constantly having to make work arounds to make the jqueryUI stuff work in IE6 and forget about trying to make it work in IE 5.5
IE6是最大的陷阱之一。我发现自己经常不得不努力使jqueryUI的东西在IE6中运行而忘记尝试使它在IE 5.5中工作
#5
1
Well I am a N00B but most of the problems I faced with Jquery' functions not working was in $("div > label") type of functions. Some times it would plain not work in IE( i guess 7) and I would have to explicitly specify it. Also the Document.Ready function wont work for me when i had loads of scripts loading in IE7. Overall Even though the above things might have been due to error on my part I find it best to avoid using ELE.children("#id")
instead prefer ELE.find(".class")
as this will give u a bit of flexibility over the layout and Because u will be doing loads of things on similiar elements(ex. copy multiple divs) My only suggestions would be to use Classes instead of IDs and use Find instead of Children. What i am trying to say here is if u use Find instead of children atleast u gain independence from change in layout of individual element as long as they are in distinct containers.(hope this is useful)
好吧,我是N00B,但我遇到的Jquery函数无法正常工作的大部分问题都是$(“div> label”)类型的函数。有时它在IE中根本不起作用(我猜7),我必须明确指定它。当我在IE7中加载大量脚本时,Document.Ready函数也不适用于我。总的来说尽管上面的事情可能是由于我的错误,我发现最好避免使用ELE.children(“#id”)而不是喜欢ELE.find(“。class”),因为这会给你一点灵活性在布局上,因为你将在类似的元素上做大量的事情(例如复制多个div)我唯一的建议是使用Classes而不是ID并使用Find而不是Children。我想在这里说的是,如果你使用Find而不是孩子,只要他们在不同的容器中就可以从单个元素的布局中获得独立。(希望这很有用)
#6
0
One bad-practice trap to avoid is doing lots of HTML generation from within your javascript. For example, I see stuff like this a lot:
要避免的一个不良做法陷阱是在javascript中进行大量的HTML生成。例如,我看到很多这样的东西:
$('<a href="'+url+'">'+text+'</a>').appendTo('#container');
Beware! 90% of the time this kind of code is generating similar markup to that which is already coming from the server. In other words, as soon as the markup for your links change you'll to have to hunt down the line of javascript and update that as well.
谨防! 90%的情况下,这种代码生成的类似标记与已经来自服务器的代码相似。换句话说,只要链接的标记发生变化,您就必须追捕javascript行并更新它。
I highly recommend using the official jQuery templates plug-in as soon as you feel that first urge to generate HTML in your javascript!
我强烈建议您在首次尝试在javascript中生成HTML时,立即使用官方jQuery模板插件!
#7
0
I've personally worked a lot with jQuery and what I can say is the problems you will face are not with jQuery but with the nature of javascript itself. You need to keep your code organized and well documented. Try following some kind of mvc (backbonejs, javascript mvc or something of the kind). AVOID GLOBAL VARIABLES. Use namespaces for what ever objects you utilize. Use the document.ready for as few events as possible. Otherwise you are going to over pollut it and again... it becomes messy.
我个人使用jQuery工作了很多,我可以说你将遇到的问题不是jQuery,而是javascript本身的性质。您需要保持代码的组织和记录。尝试使用某种mvc(backbonejs,javascript mvc或类似的东西)。避免全球变量。使用命名空间来处理您使用的对象。尽可能少地使用document.ready。否则你会过度污染它再次......它会变得混乱。
Keep a javascript nature of things as in using closures, objects and methods.
保持事物的javascript性质,如使用闭包,对象和方法。
Careful of over appending strings into the dom. Make sure you are using .load() or .clone() to get html from your template file. If you use backbone or javascriptmvc this will come inherently.
小心地将字符串附加到dom中。确保使用.load()或.clone()从模板文件中获取html。如果你使用backbone或javascriptmvc,这将是固有的。
Hope this helps and good luck!
希望这有帮助,祝你好运!