Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kendo bind HTML elements to grid selected row/dataItem

Tags:

mvvm

kendo-ui

I have the following situation (using KendoUI):

I have a grid binded to a datasource. When I select a row in the grid I invoke its "change" event to get the selected dataItem e show its values through other HTML elements.

Something like the following:

$("grid-element").kendoGrid({
    change: setElements
});

function setElements() {
    var grid = $("#grid-element").data("kendoGrid");
    var selectedItem = grid.dataItem(grid.select());

    $("#span-field1").text(selectedItem.field1);
    $("#span-field2").text(selectedItem.field2);
    $("#span-field3").text(selectedItem.field3);
}

My question is: is it possibile to achieve the same through MVVM or a better KendoUI model binding solution?

like image 527
Matteo Piazza Avatar asked Dec 06 '25 04:12

Matteo Piazza


2 Answers

So far I have found the following solution:

=== JAVASCRIPT ===
var vm = kendo.observable({
    gridSelectedItem: null,

    _field1: function() { 
        return this.get("gridSelectedItem.field1"); 
    },
    _field2: function() { 
        return this.get("gridSelectedItem.field2"); 
    }
});

$("#grid-element").kendoGrid({
    change: function(e) {
        var selectedItem = this.dataItem(this.select());
        vm.set("gridSelectedItem", selectedItem);
    }
});


=== HTML ===
<span data-bind="text: _field1"></span>
<span data-bind="text: _field2"></span>

Is there a better way?

like image 135
Matteo Piazza Avatar answered Dec 08 '25 01:12

Matteo Piazza


Indeed there you are on the right track,

Here is what I can suggest you to try:

=== JAVASCRIPT ===
var vm = kendo.observable({
    gridSelectedItem: null    
});

$("#grid-element").kendoGrid({
    change: function(e) {
        var selectedItem = this.dataItem(this.select());
        vm.set("gridSelectedItem", selectedItem);
    }
});


=== HTML ===
<span data-bind="text: gridSelectedItem.field1"></span>
<span data-bind="text: gridSelectedItem.field2"></span>

It should be slightly more compact.

like image 39
Petur Subev Avatar answered Dec 08 '25 00:12

Petur Subev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!