0

I was wondering this, in the following example, what would be the best way to handle re-use my helpers object?

var test = {
  Projects: 'an object goes here',
  helpers: require('../helpers'),

  test: function(req, res) {
    if (this.helpers.is_post(req)) {
      // tried this
      var test = this.helpers;

      this.Projects.byCode(req.params.project_code, function(project) {
        if (!project) {
          this.helpers.flash(req, 'error', 'Unable to find project.');
          // tried this
          helpers.flash(req, 'error', 'Unable to find project.');
          res.redirect('/projects');
        }
      });
    }
  }
};

I know I can't re-use variables, objects, etc in callbacks since they're not execute during the same runtime, but still there must be some kind of better/clearer way of doing such a thing?

Even if I tried to reassign this.helpers to another variable, it gives me errors saying that it is undefined.

Thanks!

1 Answer 1

4

Why do you think you cannot re-use variables inside callbacks? They are executing not only in the same runtime, but in the same thread! That's the beauty of JavaScript.

Instead, your problem is likely a misuse of this. For example, it will definitely not work without the assignment to var test = this.helpers. And even that won't work if you call the method like so:

var testIt = test.test;
testIt(req, res);

Try something like the following instead:

var helpers = require('../helpers');

var test = {
  Projects: 'an object goes here',

  test: function(req, res) {
    if (helpers.is_post(req)) {
      this.Projects.byCode(req.params.project_code, function(project) {
        if (!project) {
          helpers.flash(req, 'error', 'Unable to find project.');
          res.redirect('/projects');
        }
      });
    }
  }
};

It's really pretty nonsensical to put an entire module as a property of your object, anyway.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.