Completing the JavaScript callback override "this"
I know about call
and apply
in JavaScript, but I am currently following the following scenario.
I am using Benchmarkjs and it has an API defined like this:
.on(eventType, listener)
So, I would do for example:
/* Register the onStart callback */
suite.on('start', onStart);
My function onStart
is called so that this === suite
.
How can I do this to identify one of arguments
the onStart
?
My code looks something like this:
foo = function() {
this.suite.on('start', this.onStart);
}
I want my function to onStart
have a link to foo
.
Any suggestions?
source to share
You can call Function.prototype.bind
to create partial applications / currency functions.
.bind()
takes a context as the first parameter, and all subsequent ones passed in parameters will be used as formal parameters to call the associated function.
suite.on( 'start', this.onStart.bind( this, foo ) );
The link to foo
will now be available for onStart()
as the very first argument.
source to share