简体   繁体   中英

Passing callback function as parameter

I am calling a function like below. Here I am also passing callback function that should be called only after a particular form submit not before that.

<div onClick="myNamespace.openDialog(par1,par2,myNamespace.callback(myNamespace.cb,'p1','p2'))">OPEN DIALOG</div>

var myNamespace = myNamespace || {};
myNamespace={
     return{
        cb:function(p1,p2){alert(p1+"  cb  "+p2);},
        callback:function(f){f(arguments[1],arguments[2]);},
        openDialog:function(p1,p2,f){
          // aboutBizzNs.cb should be called here only after form submit

        }
     }
}();

The problem is alert(p1+" cb "+p2); is called just after OPEN DIALOG is clicked. It should not be like that. It should be called only when I want. What is the problem

The problem is that aboutBizzNs.callback immediately invokes the function supplied as an argument.


Compare with the following which creates and returns a closure (function) which will invoke the function supplied when it iself is invoked:

callback: function(f){
    // The f variable is bound in a closure below, which is returned immediately.
    // However, the f function is NOT invoked yet.
    // We also copy the arguments of this function invocation and expose
    // them via a variable which is also bound in the following closure.
    var boundArgs = Array.prototype.slice(arguments, 0);
    return function () {
        // Now f is invoked when this inner function is evaluated, which
        // should be in response to the event.
        return f(boundArgs[1], boundArgs[2]);}
    }
}

I'd also use apply , as in the following such than an arbitrary number of "bound" parameters can be used ..

return function () {
    return f.apply(this, boundArgs.slice(1));
}

.. but this is a fairly common operation and is already supported by Function.prototype.bind (which is part of ES5 and shim-able in other browsers). As such, the original ..

myNamespace.callback(myNamespace.cb,'p1','p2')

.. could be written as ..

myNamespace.cb.bind(this,'p1','p2')

.. for the same effect here. A difference is the this inside the callback ( cb ) function may differ as bind doesn't allow a "pass through" of this .

Or, just forget about all these special functions and simply wrap the callback as such ..

function () { myNamespace.cb('p1','p2') }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM