0

I'm using Knockout JS and Durandal JS. I want to query the database from a separate Js file and bind the data in the viewModel Js file.

I'm having a index.js file and contains a listData as an observableArray which is bound to the view(index.html). In index.js i'm calling a function to get data form another file:apiCall.js. In apiCall.js i'm calling a getJson method to get a list from database. Now, how should i bind the new list to the listData observableArray? Since Ajax works Asynchronously, all other code gets executed before getJson call. Also, return won't work as expected.

How am I supposed to do it? If I call getJson or ajax form the same viewModel file itself(index.js), it works fine because we can push data easily. Is it goot to have a separate file for only ajax calls?

index.js

var activate = function () {
    var self = this;
    self.listData(apiCall.listData());
    ...}

apiCall.js

var listData = function () {    
    $.getJSON("/api/Clients", function (data) {
        return data; 
    }
}
IRONMAN
  • 168
  • 1
  • 10

1 Answers1

0

You can't use the return value of asynchronous functions. Use callbacks.

Observables are functions. That's convenient because...

  • therefore they can serve as callbacks
  • the first argument an observable expects is the data you want to write to it
  • the first argument to an Ajax done() callback is the data that came from the server

Like this:

// index.js -------------------------------------------------------
var activate = function () {
    var self = this, apiCall = /* ... */;

    self.listData = ko.observableArray();

    apiCall.listData().done(self.listData);
}

// apiCall.js -----------------------------------------------------
var listData = function () {    
    return $.getJSON("/api/Clients"); 
}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Thanks Tomalak, It worked! But, while adding data there is another function addData in index.js and apiCall.js. In apiCall,js are two ajax calls- one for adding and the other for getting data, how to accomplish this? After adding data to the database, it should display the Data. – IRONMAN Nov 15 '13 at 10:48
  • I'm afraid I don't understand that comment. – Tomalak Nov 15 '13 at 12:39