javascript - Passing in array of functions as parameter, for each func in functions run the function -
i trying pass in array of functions parameter function x execute them within function x. somehow pass in parameters of parameters initialised within function x.
some functions include things like:
_showdata(data,type); console.log(data); $('#loading').remove();
here sample:
// called somewhere else runfunctions([$('.dashboard').remove, $('.screen-loading').remove]); var runfunctions = function(functions){ // things (var = 0; < functions.length; i++){ functions[i](); }
any ideas?
edit: sorry realised program doesn't know objects because i'm changing scope ajax call.
var runfunctions = function(functions){ $.ajax({ method: "post", url: "php/database.php", datatype: "json", data: {type:type}, success: function(data, type){ (var = 0; < functions.length; i++){ functions[i](); } } }) }
what this:
_accessdatabase( function(onsuccess){ $('.dashboard').remove(); var type = 'home'; _showdata(data,type); // doesn't know data is, how can pass through? $('.screen-loading').remove(); } ); var _accessdatabase = function(onsuccess){ $.ajax({ method: "post", url: "php/database.php", datatype: "json", data: {}, success: function(data){ onsuccess(data); } }) }
i want pass through var data onsuccess function, how can this?
solved with:
var _request_successful = function onsuccess (data){ console.log("running onsuccess"); $('.dashboard').remove(); var type = 'home'; _showdata(data,type); $('.screen-loading').remove(); } _accessdatabase(_request_successful); var _accessdatabase = function(onsuccess){ $.ajax({ method: "post", url: "php/database.php", datatype: "json", data: {}, success: function(data){ onsuccess(data); } }) }
the problem code functions you're calling within forloop aren't bound anything. take instead.
// called somewhere else runfunctions([ $('.dashboard').remove.bind($('.dashboard')) , $('.screen-loading').remove.bind($('.screen-loading')) ]); function runfunctions(functions){ // things (var = 0; < functions.length; i++){ console.log("running") functions[i](); } }
what instead this:
function call(method, objs) { objs.foreach(function (obj) { obj[method]() }) } call('remove', [$('.dashboard'), $('.screen-loading')])
here's working fiddle: https://jsfiddle.net/ogfgocp4/
to explain bit how works, don't know internal of javascript, when do: $('.dashboard').remove
, return remove
function. if call immediatly, bound object give method. if affect else, bound object it's being called from.
here's small snippet of code explains guess.
var obj = { fun: function () { console.log(this) } } var fun2 = { a: 1 } //this -> obj obj.fun() // -> window fun = obj.fun fun() // -> fun2 fun2.fun = obj.fun fun2.fun()
when call obj.fun
, this
object obj
. when affect method var
, this
become window
default object in scope. if bind function object fun2
, call immediatly, this
object fun2
.
Comments
Post a Comment