javascript - jquery - how to continue the execution of one function once another function has returned a value -
i have function called showauthorinfo performs animation, , executes other code logic once animation finished:
self.showauthorinfo = function(){ var authorid = $authorlink.attr('data-author-id'); //pl-int - determine info needs captured here var isactive = $modalinfowindow.hasclass('active'); self.$modalinfowindow.animate({ 'bottom': '0px' },200,function(){ self.$modalinfowindow.addclass('active'); self.loadauthorinfo(authorid); }) }
however, because want show , hide modal window via various function calls, executing different callbacks each time animation completed, i'd wrap animation function. question is, can use above function call custom function animation happens, , have animation function return value function, whereon can proceed?
i break function multiple functions, feel complicated, because have pass on function-specific parameters wouldn't apply cases (for example, in code above, if going call animation function, , loadauthorinfo function, animation function have accept authorid pass on loadauthorinfo, though animation function needs authorid if called showauthorinfo).
any recommendations here?
example of i'd rather not do:
self.showauthorinfo = function(){ var authorid = $authorlink.attr('data-author-id'); //pl-int - determine info needs captured here var callback = self.displayauthorcontent(); self.animateinfowindow(authorid,callback); } self.animateinfowindow = function(authorid,callback){ self.$modalinfowindow.animate({ 'bottom': '0px' },200,function(){ //create conditional if there's authorid, pass callback function, otherwise call callback function without parameters }) }
mheavers, you've tagged question promise
, means thinking along right lines.
it's maybe little appreciated jquery allows ad hoc promises formed jquery collections, $(selector).promise(type, target)
, typically @ end of longer method chain. type
defaults "fx" (the standard animation queue), , target optional (and not relevant here).
thus, self.animateinfowindow
can blissfully unaware of happen after animation kicks off has completed. needs return promise of type described above, allowing chaining self.animateinfowindow
called.
self.animateinfowindow = function() { return self.$modalinfowindow.animate({'bottom':'0px'}, 200).promise(); };
and self.showauthorinfo
can perform post-animation action without passing params self.animateinfowindow
.
self.showauthorinfo = function() { var authorid = $authorlink.data('authorid') || null; //pl-int - determine info needs captured here self.animateinfowindow().done(function() { self.$modalinfowindow.addclass('active'); self.loadauthorinfo(authorid); }); };
note, || null
in first line ensure authorid
not undefined
. (slightly more complicated if authorid of 0 (zero) valid).
the other thing ensure self.loadauthorinfo
tollerant of being passed null
.
Comments
Post a Comment