Mozzan
Mozzan

Reputation: 283

How to simplify my javascript code(ajax)

I use ajax in my code. I have to call connectHost() from $('SyncDataPort0') to $('SyncDataPort5'),

function connectHost()
{
    ajaxFrame($('SyncDataPort0').value, getConnectStatus);
}

function getConnectStatus(transport) 
{
    try {
        rs = transport.responseText;
        if(rs == 'OK') {
            //$('SyncDataState0').innerHTML = 'ok';
            addStateMsg($('ConnectTest'),getMsg('msgConnectOk'));
        } else //NOT OK

        addStateMsg($('ConnectTest'),getMsg('msgConnectNotOkResult').replace('%s',rs));
    }catch(e){alert(e)};
}

function ajaxFrame(url, pars, onCompleteFun)
{
if (3 in arguments)
    addStateMsg(arguments[3],getMsg('msgDataSending'),0);

new Ajax.Request(url,
{
    method:'post',
    parameters:pars,
    onComplete: function(transport)
    {
        var rs = transport.responseText;
        if('logout' == rs)
            location.href='/index.php?menu=logout';
        else if('' == rs)
        {
            //do nothing
        }else
            onCompleteFun.apply(this,[transport]);
    },
    onFailure:function()
    {
        debug('Load Data Failure!');
    }
});
return true;
}

The question is how can i implement the function without reproducing the getConnectStatus callback function???

Upvotes: 0

Views: 81

Answers (1)

jfriend00
jfriend00

Reputation: 707308

If you use an inline function declaration, you can refer to variables in the parent scope and you can pass the port to your connectHost() function.

function connectHost(portNum)
{
    ajaxFrame($('SyncDataPort' + portNum).value, function(transport) {
        // you can refer to portNum here in the callback
        try {
            rs = transport.responseText;
            if(rs == 'OK') {
                //$('SyncDataState0').innerHTML = 'ok';
                addStateMsg($('ConnectTest'),getMsg('msgConnectOk'));
            } else //NOT OK

            addStateMsg($('ConnectTest'),getMsg('msgConnectNotOkResult').replace('%s',rs));
        } catch(e) {alert(e)};
    });
}

If you want getConnectStatus() to still be its own function, then you can use an inline stub function like this:

function connectHost(portNum)
{
    ajaxFrame($('SyncDataPort' + portNum).value, function(transport) {
        getConnectStatus(transport, portNum);
    });
}

And getConnectStatus() will have the portNum as the second argument. You can pass as many arguments through to the callback as you like this way.


If getConnectStatus() needs the value of this preserved, then you would do this:

function connectHost(portNum)
{
    ajaxFrame($('SyncDataPort' + portNum).value, function(transport) {
        getConnectStatus.call(this, transport, portNum);
    });
}

Upvotes: 1

Related Questions