1

This must have been asked before, I am just not sure exactly what to search for, I can delete the question if someone links to a duplicate! Thanks.

If I have a javascript function which calls an external api, how can I pass other parameters before the data is returned? E.g. using Google Apps, the tasks api returns a list of the user's tasks like so:

google.script.run
    .withSuccessHandler(showTasks) // showTasks callback function
    .getTasks(taskListId);
}

/* Show the returned tasks on the page. */
function showTasks(tasks) {
    // tasks is now an object of tasks returned by google
    ...

However, I want to do this:

var tasksListNumber = 1;  

google.script.run
    .withSuccessHandler(showTasks(null, tasksListNumber)) // showTasks callback function
    .getTasks(taskListId);
}

/* Show the returned tasks on the page. */
function showTasks(tasks, tasksListNumber) {
    // tasks is now an object of tasks returned by google
    // tasksListNumber is 1
    ...

Does the solution involve using the bind function somehow?

timhc22
  • 7,213
  • 8
  • 48
  • 66
  • 1
    In the snippet you posted, you can simply access `taskListNumber` from the body of `showTasks` (it is not local, but still visible). Is your actual use case more involved? – Igor Raush Oct 25 '16 at 00:23
  • a little bit, because the google function is just one example that is used, events are used too: `$('#tasklist').bind('change', loadTasks);` needs to be `$('#tasklist1').bind('change', loadTasks(taskListNumber));` too. I guess accessing in the way you suggested is the best way, or writing something custom for each different scenario – timhc22 Oct 25 '16 at 16:19
  • I guess accessing as the parent function's variable is the best way: http://stackoverflow.com/questions/3946177/javascript-is-it-possible-to-pass-a-variable-into-a-callback-function-that-is-a – timhc22 Oct 25 '16 at 16:24

1 Answers1

2

Not used Google Aps api. But reading there docs -> The server's return value is passed to the function as the first argument, and the user object (if any) is passed as a second argument. So to me, something like ->

google.script.run
    .withUserObject(tasksListNumber)
    .withSuccessHandler(showTasks) // showTasks callback function
    .getTasks(taskListId);
}

In your code your basically executing showTasks(null, tasksListNumber) instantly.

Keith
  • 22,005
  • 2
  • 27
  • 44