JavaScript中的流控制 [英] Flow control in JavaScript

查看:121
本文介绍了JavaScript中的流控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在JavaScript中编写此流程控件?

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:


  1. 您应该将 references 中的数组构建到您的函数中。这意味着你不用(),因为你只想传递引用,而不是调用函数的结果!

  2. 您将不得不处理这样一个事实:从对象的属性获取函数的引用将不会记住与该对象的关系。因此,流代码无法知道如何使用MyLib作为上下文引用来调用函数。如果这很重要,您将需要创建在正确的上下文中运行成员函数的函数。

  1. You 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!
  2. You'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.

运行函数在正确的上下文中,您可以拼凑一些类似Prototype框架提供的bind函数(以及许多其他函数,Functional.js)或 $ .proxy()。它并不难,可能看起来像这样:

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:

function bindToObject(obj, func) {
  return function() {
    func.apply(obj, arguments);
  }
}

然后你会像这样使用它:

then you'd use it like this:

MyLib.flow([
  bindToObject(MyLib, MyLib.get),
  bindToObject(MyLib, MyLib.save),
  bindToObject(MyLib, MyLib.alert)
]);

如果你需要传入参数,你可以修改 bindToObject:

If you need for parameters to be passed in, you could modify "bindToObject":

function bindToObject(obj, func) {
  var preSuppliedArgs = Array.prototype.slice.call(arguments, 2);
  return function() {
    func.apply(obj, preSuppliedArgs.splice(arguments));
  }
}

假设您希望在调用bound函数将其添加到参数列表的末尾。在你的情况下,我怀疑你是否想要这样做,所以你可以放弃那个splice()电话。

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.

这篇关于JavaScript中的流控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆