0

I have a koa app which has a bunch of functions split up into separate files. When one route is called I need to pass the context this to another function (which is also a route) in an separate file.

File a.js route - http://127.0.0.1:3000/foo

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

File b.jsroute - http://127.0.0.1:3000/bar

var a = require('a');

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

I want to be able to yield a.foo() with the current context (this) and have it operate like it is being called by the normal router.

sbarow
  • 2,759
  • 1
  • 22
  • 37
  • I think your shared functionality is better placed in a middleware where both `/foo` and `/bar` routes can call `yield this.sharedFeature(opts)`. If you want to go your way, then just do `yield a.foo.bind(this)` – kilianc Jun 22 '14 at 13:25
  • Hmmmm, @kilianc seems like doing `yield a.foo.bind(this)` doesn't actually call the function nor return from the function? Is there something special you need to do in `a.foo` ? – sbarow Jun 22 '14 at 13:31
  • a.foo is a generator right? then you don't have to do anything in particular, try `a.foo.call(this)` but `.bind` should work too – kilianc Jun 22 '14 at 15:45
  • @kilianc you were right, that actually works. If you put that as an answer I will accept. Thanks for your help. – sbarow Jun 22 '14 at 16:04

2 Answers2

2

I think your shared functionality is better placed in a middleware where both /foo and /bar routes can call yield this.sharedFeature(opts).

If you want to go your way, then just do yield a.foo.call(this)

kilianc
  • 7,397
  • 3
  • 26
  • 37
0

There are few problems there. one is you have to return the value (or pass the value back in the callback). Also there is a problem how a.js is required. You need to add the path to it "./a" (or where ever you store it), not "a". Here is the revision (Note that I'm not including koajs in the code since this is just javascript/nodejs issue):

// 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"

This is how the context of bar() can be passed to 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"
Ben
  • 5,024
  • 2
  • 18
  • 23
  • Not really what I am looking for, specifically I need the context from bar to be passed to foo. Regarding how `a` is required, its just an example. – sbarow Jun 20 '14 at 16:22
  • Ok, I'll revise the answer for that – Ben Jun 20 '14 at 16:35