Search code examples
javascriptjquerykendo-uikendo-treeviewkendo-datasource

Access dataItem inside transport.read function


This question is a mirror from this post on Telerik's Forum that I have posted yesterday.

I have a TreeView with HierarchicalDataSource and my question is simple: Can I access the current dataItem in the transport.read function?

For instance, consider this code:

new kendo.data.HierarchicalDataSource({
    transport: {
        read: function(options) {
            // Here i'll prepare my url to be called
            return "my/controller/" + dataItem.Id;
        }
    }
});

I want to access the dataItem's properties of the current expanding node inside the read function. Is this possible?

I have tried many ways but the scope inside that function gives me access of nothing outside it.

UPDATE:

@OnaBai suggestion worked with - in my case - Value property, given the following model:

{
    id: "Value",
    hasChildren: "HasChildren"
}; 

But I want to be able to access more that just Id but the entire dataItem. I've tried to add dataItem's - or request - properties to the model but it doesn't worked:

{
    id: "Value",
    hasChildren: "HasChildren",
    fields: {
        ParentId: { type: "string" }
    }
}; 

ParentId comes from the resquest and its accesible in dataItem, but not in options inside read function. There's another way to do that ?

UPDATE 2:

A tricky way of doing this can be achieved by setting the model's id to uid:

{
    id: "uid"
}

The function will receive the uid and then you can get it from dataSource with, e.g. dataSource.getByUid().


Solution

  • Assuming that Id the id defined in your model, you should do:

    new kendo.data.HierarchicalDataSource({
        transport: {
            read: function(options) {
                return "my/controller/" + options.Id;
            }
        }
    });
    

    See an example here : http://jsfiddle.net/OnaBai/mE4zZ/2/

    EDIT: If you need to access the full model then known the id you can use get method on the DataSource for getting the item.

    Example:

    var ds = new kendo.data.HierarchicalDataSource({
        transport: {
            read: function(options) {
                if (options.Id) {
                    var item = ds.get(options.Id);
                    // Do whatever else you need with Item
                }
                return "my/controller/" + options.Id;
            }
        }
    });
    

    Modified JSFiddle here http://jsfiddle.net/OnaBai/mE4zZ/3/