1

I have this piece of code

function main(b)
{
    b.on('func1', onFunc1);
    b.on('func2', onFunc2);
}

function onFunc1(a)
{
  console.log(a); //prints (for example) 2
  console.log(b); //is this possible?
}

So my question is, is there any way that I can pass to function 'onFunc1' variable named 'b'?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
anagarD
  • 151
  • 2
  • 9

2 Answers2

1

You can do the following:

function main(b) {
    b.on('func1', function(){ onFunc1(b); });
    b.on('func2', function(){ onFunc2(b); });
}

function onFunc1(a) {
  console.log(a); //prints (for example) 2
  console.log(b); //is this possible?
}

Doing it this way, the anonymous function will get called, and will call your handler passing the function that you want it to pass.

frosty
  • 21,036
  • 7
  • 52
  • 74
-1

As it is written in the documentation you can insert an object containing data as the second field of the call:

function myHandler( event ) {
  alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );

For further info pls see jQuery on documentation

morels
  • 2,095
  • 17
  • 24
  • What makes you think the OP uses jQuery? – Felix Kling Oct 07 '15 at 15:01
  • Because in this case @angarD has written code that uses `.on()`, that is a jQuery function and what it does is compatible with his question. If it is not @angarD is free to say the contrary. If you have any better idea on that framework should be please tell me. – morels Oct 07 '15 at 15:31
  • `.on` is a pretty common name for a method that binds event handlers. It's by no means special or specific to jQuery. E.g. [Node's `EventEmitter`](https://nodejs.org/api/events.html#events_emitter_on_event_listener) uses `.on` as well. `b` might be an instance of `EventEmitter`. Or maybe it's the OP's own implementation. `b` could just be `{on: function(event, handler) { /* do something */ }}`. Assuming this is jQuery is a bit of a stretch. – Felix Kling Oct 07 '15 at 15:35
  • Thank you @FelixKling, reading the link you posted and looking around for similar questions I understood better. – morels Oct 08 '15 at 07:10
  • Actually I was working with Node and EventEmitter. JQuery tag was accidental. I wasn't even aware that I put that tag also. Sorry for late response. – anagarD Oct 12 '15 at 09:24