J.Olufsen
J.Olufsen

Reputation: 13915

How to invoke function call if it is defined as var?

I'm getting data from server using JQuery and JSON. I defined getBooksDoneFunc as variable because I need to be able to call this function not only once (when getBooks is done) . Unfortunately, I cannot call getBooksDoneFunc from inside of signInOK as window["getBooksDoneFunc"]();. Why? What is the best way to call this function?

function getBooks(){     return $.getJSON( "bookstore.json" );             }

var getBooksDoneFunc = function(json) { 
         $.each(json.books, function(i, json){ .......... });

}

getBooks().done(getBooksDoneFunc);

function signInOK(){
         window["getBooksDoneFunc"]();
}

PS. The idea for window["getBooksDoneFunc"](); was taken from SO answer

UPDATE:

var booksJSON = {};
window["getBooksDoneFunc"](booksJSON);

getBooksDoneFunc must be called with parameters nevertheless the call to getBooksDoneFunc fails. signInOK is defined outside of $(document).ready(function(){ }); but called inside of it.

Upvotes: 1

Views: 194

Answers (3)

ron tornambe
ron tornambe

Reputation: 10780

I would do this a bit differently, although I do not really understand the signInOK() function. How will it receive the "json" data. I would reconstruct the getBooks function and rethink the signInOk function. Here's a start:

function getBooks() {
    $.getJSON("bookstore.json").done(function (json) {
        getBooksDoneFunc(json);
    });
}

var getBooksDoneFunc = function(json) { 
     $.each(json.books, function(i, json){ .......... });

};

...

getBooks();

function signInOK(){
     getBooksDoneFunc("some json data");
}

Upvotes: 0

Mathijs Flietstra
Mathijs Flietstra

Reputation: 12974

Try:

function getBooks(){
  return $.getJSON( "bookstore.json" );
}

window.getBooksDoneFunc = function(json) { 
  $.each(json.books, function(i, json){ .......... });
}

getBooks().done(getBooksDoneFunc);

$(document)ready(function() {
  function signInOK(){
    var booksJSON = {};
    window.getBooksDoneFunc(booksJSON);
  }
});

Upvotes: 2

xdazz
xdazz

Reputation: 160863

If window["getBooksDoneFunc"](); works, then does getBooksDoneFunc(), the idea of using window is when you want to access a global function but you don't know the function name which is stored in a variable.

In your case, put a hardcoding string is mean less, just do getBooksDoneFunc() is the same, because you already store the function self (not the string of function name) in the variable.

The thing that won't work is that if the variable is not global, please check the scope.

Upvotes: 1

Related Questions