Is it possible to write this flow control in JavaScript?
MyLib.get = function() { /* do something */ next(); };
MyLib.save = function() { /* do something */ next(); };
MyLib.alert = function() { /* do something */ next(); };
MyLib.flow([
MyLib.get(),
MyLib.save(),
MyLib.alert()
], function() {
// all functions were executed
});
Yes, but two things to know:
(), because you just want to pass through the reference, not the result of calling the function!thiscontext reference. If that’s important, you’ll want to create functions that run your “member” functions in the right context.To run the functions in the right context, you can cobble together something like the “bind” function supplied by the Prototype framework (and also, among many others, Functional.js), or
$.proxy()from jQuery. It’s not that hard and would probably look like this:then you’d use it like this:
If you need for parameters to be passed in, you could modify “bindToObject”:
That assumes you’d want additional arguments passed when the “bound” function is called to be tacked on to the end of the argument list. In your case, I doubt you’d want to do that, so you could leave off that “splice()” call.