Home:ALL Converter>Flow control in JavaScript

Flow control in JavaScript

Ask Time:2010-12-21T07:51:53         Author:Jardon Mayer

Json Formatter

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
});

Author:Jardon Mayer,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/4495110/flow-control-in-javascript
Pointy :

Yes, but two things to know:\n\n\nYou should build the array from references to your functions. That means you leave off the (), because you just want to pass through the reference, not the result of calling the function!\nYou're going to have to deal with the fact that getting references to functions from properties of an object will not \"remember\" the relationship to that object. Thus, the \"flow\" code would have no way to know how to invoke the functions with \"MyLib\" as the this context reference. If that's important, you'll want to create functions that run your \"member\" functions in the right context.\n\n\nTo 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:\n\nfunction bindToObject(obj, func) {\n return function() {\n func.apply(obj, arguments);\n }\n}\n\n\nthen you'd use it like this:\n\nMyLib.flow([\n bindToObject(MyLib, MyLib.get),\n bindToObject(MyLib, MyLib.save),\n bindToObject(MyLib, MyLib.alert)\n]);\n\n\nIf you need for parameters to be passed in, you could modify \"bindToObject\":\n\nfunction bindToObject(obj, func) {\n var preSuppliedArgs = Array.prototype.slice.call(arguments, 2);\n return function() {\n func.apply(obj, preSuppliedArgs.splice(arguments));\n }\n}\n\n\nThat 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.",
2010-12-20T23:59:23
yy