2

I've a typical use case (may be too specific to my use case).

I've a piece of like this:

var x=0,y=10;

var data = {"callback" : function(x,y) {console.log(x,y)}}

some where in the code flow im asynchronously call above anonymous function

call(data.callback);

my problem is in second piece of code i don't have data of x,y to pass on while calling function. So, is there any way we can attach data(x,y variables data) while declaration of function itself?

Edit 1:

@Kursad Gulseven, because, to make it simple i showed like that.

But, in actual case, "data", "callback" are dynamic names. So, i can't simple use data.callback.

Though i do that, i can't have variables (with data), where i'm trying to call my anonymous function . Because calling anonymous function is again from another asynchronous function which is what issue here.

Hope its clear and makes some sense.

3
  • 1
    Why not use data.callback(x,y);? Commented Nov 4, 2014 at 6:45
  • 3
    call(data.callback.bind(data, 1, true, "anything else u need")); you can also use call/apply at run-time, bind() composes a new function Commented Nov 4, 2014 at 6:50
  • @dandavis, your answer seems to solve my problem. let check it. Commented Nov 4, 2014 at 7:01

2 Answers 2

1

Inject x and y in your data object, when they are available.

data = {
  x: null,
  y: null,
  "callback": function(x, y) {
    x = x || this.x;
    y = y || this.y;
    console.log(x, y);
  }
}

data.x = 0
data.y = 10;

// I'm assuming here you have a way to know how the "data" object is called
// and how to access it. (the obejct it's attached to)
// For simplicity, I used a global

var dataName = 'data',
  callbackName = 'callback';

//using a wrapper function without parameters, like in your example
// call(data.callback);


//calling without parameters
window['data']['callback']();

// calling with parameters
window[dataName][callbackName](15, 25);

Note: If you're obtaining x and y through some kind of async call, you might wanna check the promise pattern

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

Comments

1

I'm not sure why you can't set data.x and data.y then read those values as the other answer mentions. If that is unsatisfactory, then perhaps you could build a closure (a function with x and y preset) when you obtain x and y, like so:

function setCallback(x,y){
  return (function(){console.log(x,y);});
}
data.callback=setCallback(0,10);

data.callback is then the same function you have except with x and y preset to the example values you provided.

Executing data.callback(); then results in 0 10 in console.

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.