Javascript在获得响应之前分配变量

时间:2014-03-25 10:06:04

标签: javascript jquery ajax

我不确定什么是正确的问题,但我会尝试用我当前的工作代码解释:

var container, loader
switch(section){
    case 'A':
        container = $('#list .container')
        loader = $('#surveylist')
        var r = postToServer(data, loader)
        if(r.cstatus === true){
            container.html(r.content)
        }
    break
    case 'B':
        container = $('#control .container')
        loader = container
        var r = postToServer(data, loader)
        if(r.cstatus === true){
            container.html(r.content.panelB)
        }
    break
    case 'C':
        container = $('#content .container')
        loader = container
        var r = postToServer(data, loader)
        if(r.cstatus === true){
            $('#surveyElements').sortable();
            $('textarea').autosize();
            container.html(r.content.panelC)
        }
    break
}

正如您所看到的,我正在重复相同的代码,并希望简化该方法,但不确定在Google中搜索的正确术语。基本上我想要实现的是这种结构:

var container, loader, test
switch(section){
    case 'A':,
        container = $('#list .container')
        loader = $('#surveylist')
        test =  container.html(r.content)
    break
    case 'B':
        container = $('#control .container')
        loader = container
        test =  container.html(r.content.panelB)

    break
    case 'C':
        container = $('#content .container')
        loader = container
        test = container.html(r.content.panelC)
    break
}
var r = postToServer(data, loader)
if(r.cstatus === true){
    // what is the right method to put 'test' here?
}

或者,如果你们有任何重构此代码的建议?

1 个答案:

答案 0 :(得分:1)

它只是一个草案,仍然可以进行优化,但可能有所帮助。

var sections = {
    A: {
        container: $('#list .container'),
        loader: $('#surveylist'),
        getTest: (function(container, r){ return container.html(r.content) })
    },
    B: {
        container: $('#control .container'),
        loader: $('#control .container'),
        getTest: (function(container, r){ return container.html(r.content.panelB) })
    },
    C: {
        container: $('#content .container'),
        loader: $('#content .container'),
        getTest: (function(container, r){ return container.html(r.content.panelC) })
    },
};
var sectionEntry = sections[section];
r = postToServer(data, sectionEntry.loader);
if(r.cstatus === true){
    test = sectionEntry.getTest(sectionEntry.container, r);
}