Reputation: 10049
I'm working with MooTools and I have a problem with a callback function. This is a little exemple:
function func1(callback){
var event = 'something';
callback(event);
}
function func2(data){
}
var Obj = new Class({
initialize: function(){
this.data = "data";
//there I want to use func1 and use func2 as callback and this.data as argument of func2
}
});
So I try
func1(function(){
func2(this.data);
});
But I can't use this.data in an anonymous function because this is not the same context.
And
func1(func2)
This didn't works because I can't pass this.data as argument.
This is juste a simple exemple, func1 comes from a library so I can't edit it.
Upvotes: 0
Views: 797
Reputation: 3903
So the library you are using allows you to supply a callback function, but it only takes one parameter.
function mycallback(data){
//now i see my data
}
Let's call this library function libfunc, and you're calling it like this:
libfunc(param1, param2, mycallback);
The lib function returns its own data to your callback function. So far so good.
Now you need TWO parameters, let's call them data, and extra. You tried:
function mycallback(data, extra){
}
but the callback function will only pass info onto the first parameter, right?
do this:
libfunc(param1, param2, mycallback('hello'));
now your mycallback should return a function in itself:
function mycallback(extra){
return function(data){
//now both extra and data are visible
}
}
mycallback('hello') returns a function that takes one parameter, which is compatible with your library callback function; yet it binds the 'hello' extra value to the function itself.
Upvotes: 0
Reputation: 11315
How about:
function func1(callback, data){
var event = 'something';
callback(event, data);
}
function func2(data, data){
}
var Obj = new Class({
initialize: function(){
this.data = "data";
//there I want to use func1 and use func2 as callback and this.data as argument of func2
}
});
And then:
func1(func2, this.data);
Upvotes: 1