Yelo Flux
Yelo Flux

Reputation: 23

Node.js - Better way to manage javascript scopes between callbacks?

I'm working with Node.JS and have two objects that I move between via callbacks. I came up with a solution to maintain scope references to the correct object. I'm trying to figure out if there's a better way to do this, or if this is good practice.

function Worker () {}

Worker.prototype.receiveJob = function(callback, bossReference) {
  this.doJob(callback, bossReference);
};

Worker.prototype.doJob = function(callback, bossReference) {
  callback.call(bossReference);
  // callback(); // this will not work
};

function Boss () {
  this.worker = new Worker();
}

Boss.prototype.delegateJob = function() {
  this.worker.receiveJob(this.whenJobCompleted, this);
};

Boss.prototype.whenJobCompleted = function() {
  this.sayGoodJob();
};

Boss.prototype.sayGoodJob = function() {
  console.log('Good job');
};

var boss = new Boss();
boss.delegateJob();

Upvotes: 2

Views: 193

Answers (1)

Jonathan Ong
Jonathan Ong

Reputation: 20335

use Function.prototype.bind()

function Worker () {}

Worker.prototype.receiveJob = function(callback) {
  this.doJob(callback);
};

Worker.prototype.doJob = function(callback) {
  callback()
};

function Boss () {
  this.worker = new Worker();
}

Boss.prototype.delegateJob = function() {
  this.worker.receiveJob(this.whenJobCompleted.bind(this));
};

Boss.prototype.whenJobCompleted = function() {
  this.sayGoodJob();
};

Boss.prototype.sayGoodJob = function() {
  console.log('Good job');
};

var boss = new Boss();
boss.delegateJob();

you won't need those silly bossReferences aftewards unless you need it in your function

Upvotes: 1

Related Questions