javascript - Passing callback function as parameter -
i calling function below. here passing callback function should called after 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 called here after form submit } } }();
the problem alert(p1+" cb "+p2);
called after open dialog
clicked. should not that. should called when want. problem
the problem aboutbizzns.callback
immediately invokes function supplied argument.
compare following creates , returns closure (function) invoke function supplied when iself invoked:
callback: function(f){ // f variable bound in closure below, returned immediately. // however, f function not invoked yet. // copy arguments of function invocation , expose // them via variable bound in following closure. var boundargs = array.prototype.slice(arguments, 0); return function () { // f invoked when inner function evaluated, // should in response event. return f(boundargs[1], boundargs[2]);} } }
i'd use apply
, in following such arbitrary number of "bound" parameters can used ..
return function () { return f.apply(this, boundargs.slice(1)); }
.. but common operation , supported function.prototype.bind
(which part of es5 , shim-able in other browsers). such, original ..
mynamespace.callback(mynamespace.cb,'p1','p2')
.. written ..
mynamespace.cb.bind(this,'p1','p2')
.. same effect here. difference this
inside callback (cb
) function may differ bind
doesn't allow "pass through" of this
.
or, forget these special functions , wrap callback such ..
function () { mynamespace.cb('p1','p2') }
Comments
Post a Comment