user2012783
user2012783

Reputation: 193

kendo datasource.fetch scope

im trying to create a function that simple returns a record from a remote source by the ID passed using Kendo's dataSource. however when i set the 'data' variable from within 'dataSource.fetch' the 'data' object still remains undefined. how do i set the 'data' object from within 'dataSource.fetch' so that i can return it.

 function getUserById(id){

  var data;

  var dataSource = new kendo.data.DataSource({
    transport: {
      read: {
        url: "/data/users/",
        dataType: "jsonp"
      }
    },
    schema: {
      model: { id: "id_usr" }
    },
    serverFiltering: true,
    filter: { field: "id_usr", operator: "eq", value: id }
  });

  dataSource.fetch(function() {
    var dataItem = dataSource.get(id);
    if(dataItem){
      data = dataItem;
    }
  });

  return data;
}

user = getUserById("lrobinson");
name = user.fname+" "+user.lname;

Heres an example http://jsbin.com/IKazEHe/2/edit?js,console

Upvotes: 1

Views: 3083

Answers (1)

Atanas Korchev
Atanas Korchev

Reputation: 30671

This happens because the fetch method is asynchronous. It will be done only when the "/data/users/" service finished loading. This is why fetch accepts a callback which is executed only when the response from the service has been received.

One way to deal with this is to make the ajax request synchronous by setting async to false:

var dataSource = new kendo.data.DataSource({
    transport: {
      read: {
        url: "/data/users/",
        dataType: "jsonp",
        async: false /* make it synchronous (basically JAX ;))
      }
    },
    schema: {
      model: { id: "id_usr" }
    },
    serverFiltering: true,
    filter: { field: "id_usr", operator: "eq", value: id }
  });

Upvotes: 1

Related Questions