Hug*_*are 51 javascript jquery code-organization
我最近一直在努力理解组织jQuery代码的最佳方法.我之前问了另一个问题,我认为我不够具体(在这里的问题中找到).
我的问题是,你做一个应用程序越丰富,你的客户端就越快失控.考虑这种情况......
//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!!
Run Code Online (Sandbox Code Playgroud)
现在这种情况并非不可能.我并不是说这是正确的方法,但是在jQuery命令中发现自己的几个级别并开始怀疑在屏幕开始融化之前可以添加多少逻辑并不罕见.
我的问题是人们如何管理或组织限制代码的复杂性?
我列出了我在其他帖子中的表现 ......
Joh*_*sig 49
只想添加前面提到的内容:
$.each(container.children(), function(j,w) {
$(w).unbind().change(function() { ... });
});
Run Code Online (Sandbox Code Playgroud)
可以优化为:
container.children().unbind().change(function() { ... });
Run Code Online (Sandbox Code Playgroud)
这一切都与链接有关,这是简化代码的好方法.
Dav*_*ert 18
到目前为止,我这样做:
// 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
});
});
}
});
Run Code Online (Sandbox Code Playgroud)
在JavaScript中,函数是第一类对象,因此可以用作变量.
嗯,首先,拥有一个理解javascript的好IDE可以提供很大帮助,即使只是为了识别匹配的分界线(括号,parens等).
如果你的代码开始变得那么复杂,可以考虑制作自己的静态对象来组织混乱 - 你不必非常努力地保持一切匿名.
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();
Run Code Online (Sandbox Code Playgroud)