Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passing user-defined variables to the callback function #1

Closed
davelandry opened this issue Oct 14, 2015 · 2 comments
Closed

passing user-defined variables to the callback function #1

davelandry opened this issue Oct 14, 2015 · 2 comments

Comments

@davelandry
Copy link

I have an ES6 Class function that I'd like to invoke as a callback function, but it loses the scope of this when I call it with timer(callback).

Any way we can pass a custom variable to the callback function? I'm not quite sure how the syntax would even look, as I wouldn't want to override the delay and time variables.

@mbostock
Copy link
Member

Did you consider using function.bind or a closure? Say you have an instance of your class (here described as a literal, but the use of ES6 classes or fields inherited properties doesn’t affect the solution):

var fred = {
  hello: function() {
    console.log("Hi, my name is " + this.name + ".");
    return true;
  },
  name: "Fred"
};

Invoking the hello method:

fred.hello(); // prints "Hi, my name is Fred.", returns true

Invoking this method by timer using a closure:

timer(function() {
  return fred.hello();
});

Invoking this method by timer using function.bind:

timer(fred.hello.bind(fred));

Note that you can also use a closure to pass extra arguments to your callback. For example, say you have a function:

function hello(name) {
  console.log("Hi, my name is " + name + ".");
  return true;
}

Invoking this method by timer using a closure:

timer(function() {
  return hello("Fred");
});

@davelandry
Copy link
Author

Egg on my face, obviously the bind works great. Thanks so much for the thorough response and great work with these new modules!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants