0

我有一个koa应用程序,它有一堆功能被分成单独的文件。当调用一个路由时,我需要将上下文传递this给单独文件中的另一个函数(这也是一个路由)。

文件a.js路径 -http://127.0.0.1:3000/foo

exports.foo = function *() {
  this.body = 'Some Value';
}

文件b.js路径 -http://127.0.0.1:3000/bar

var a = require('a');

exports.bar = function *() {
  this.body = yield a.foo(); // this obviously doesn't work.
}

我希望能够yield a.foo()使用当前上下文 ( this) 并让它像普通路由器调用它一样运行。

4

2 回答 2

2

我认为您的共享功能最好放在一个中间件中,其中/foo/bar路由都可以调用 yield this.sharedFeature(opts)

如果你想走自己的路,那就去做吧yield a.foo.call(this)

于 2014-06-22T16:10:26.750 回答
0

那里几乎没有问题。一种是您必须返回值(或在回调中将值传回)。还有一个问题是如何需要 a.js。您需要将路径添加到它“./a”(或您存储它的位置),而不是“a”。这是修订版(请注意,我没有在代码中包含 koajs,因为这只是 javascript/nodejs 问题):

// a.js
exports.foo = function() {
  this.body = 'Some Value';
  return this;
}

// b.js
var a = require('./a');  // assumes a.js is in same directory as b.js

exports.bar = function () {
  var aThis =a.foo(); 
  console.log(aThis.body);
};

// c.js
var b = require('./b');

b.bar();   // <<<<< prints "Some Value"

这是如何将 bar() 的上下文传递给 foo() 的:

// a.js
exports.foo = function(bScope) {
  console.log("this is bValue of b scope: %s", bScope.bValue);
}

// b.js
var a = require('./a');

exports.bar = function () {
  this.bValue = "value of b";
  a.foo(this);
}

// c.js
var b = require('./b');

b.bar();   // <<<<<<<< prints "this is bValue of b scope: value of b"
于 2014-06-20T15:59:09.723 回答