我最近一直在努力理解组织jQuery代码的最佳方法。我之前问了另一个问题,我想我还不够具体(found in this question here)。
我的问题是,你制作的应用程序越丰富,你的客户端就越快失控。考虑这种情况..。
//Let's start some jQuery
$(function() {
var container = $("#inputContainer");
//Okay let's list text fields that can be updated
for(var i=0; i < 5; i++) {
//okay let's add an event for when a field changes
$("<input/>").change(function() {
//okay something changed, let's update the server
$.ajax({
success:function(data) {
//Okay - no problem from the server... let's update
//the bindings on our input fields
$.each(container.children(), function(j,w) {
//YIKES!! We're deep in here now!!
$(w).unbind().change(function() {
//Then insanity starts...
}); // end some function
}); //end some loop
} // what was this again?
}); //ending something... not sure anymore
}).appendTo(container); //input added to the page... logic WAY split apart
}; //the first loop - whew! almost out!
}); //The start of the code!!
现在这种情况并不是不可能的。我并不是说这是正确的方法,但是你经常会发现自己在jQuery命令中的几个级别,并开始怀疑在屏幕开始融化之前还能添加多少逻辑。
我的问题是,人们如何管理这一点或如何组织以限制其代码的复杂性?
...
发布于 2008-10-31 23:08:23
我只想补充一下前面提到的内容:
$.each(container.children(), function(j,w) {
$(w).unbind().change(function() { ... });
});
可以优化为:
container.children().unbind().change(function() { ... });
这一切都是关于链接的,这是一种简化代码的好方法。
发布于 2008-10-30 21:37:49
到目前为止,我这样做:
// initial description of this code block
$(function() {
var container = $("#inputContainer");
for(var i=0; i < 5; i++) {
$("<input/>").changed(inputChanged).appendTo(container);
};
function inputChanged() {
$.ajax({
success: inputChanged_onSuccess
});
}
function inputChanged_onSuccess(data) {
$.each(container.children(), function(j,w) {
$(w).unbind().changed(function() {
//replace the insanity with another refactored function
});
});
}
});
在JavaScript中,函数是一级对象,因此可以用作变量。
发布于 2008-10-30 21:32:10
好吧,首先,拥有一个理解javascript的好的IDE会有很大的帮助,即使只是识别匹配的分界(大括号、括号等)。
如果您的代码真的变得如此复杂,请考虑创建您自己的静态对象来组织混乱-您不必费力地保持所有内容都是匿名的。
var aCustomObject = {
container: $("#inputContainer"),
initialize: function()
{
for(var i=0; i < 5; i++)
{
$("<input/>").changed( aCustomObject.changeHandler );
}
},
changeHandler: function( event )
{
$.ajax( {success: aCustomObject.ajaxSuccessHandler} );
},
ajaxSuccessHandler: function( data )
{
$.each( aCustomObject.container.children(), aCustomObject.updateBindings )
},
updateBindings: function( j, w )
{
$(w).unbind().changed( function(){} );
}
}
aCustomObject.initialize();
https://stackoverflow.com/questions/251814
复制相似问题