Kendo binding. View is not updating when changing the viewmodel

833 Views Asked by At

For some reason beyond me, my view doesn't get updated when changing the viewmodel. What am I doing wrong here?

It displayes:
Test1 100
Test2 200

When I expect:
Test1 300
Test2 400

Javascript:

var testModel = kendo.data.Model.define({
    fields: {
        "Name": {
            type: "text"
        },
        "Amount": {
            type: "number"
        }
    }
});

testViewModel = new kendo.observable({
    Data: [
        new testModel({ "Name": "Test1", "Amount": 100 }),
        new testModel({ "Name": "Test2", "Amount": 200 })
    ]
});

kendo.bind("#test", testViewModel.Data);
var data = testViewModel.Data;
data[0].Amount = 300;
data[1].Amount = 400;
testViewModel.set("Data", data);

HTML:

<div id="test" data-bind="source: Data" data-template="testTemplate"></div>
<script id="testTemplate" type="text/x-kendo-template">
    <div>
        <span data-bind="text: Name"></span>
        <span data-bind="text: Amount"></span>
    </div>
</script>
2

There are 2 best solutions below

0
On

Apparently I needed to set a trigger to update the template, after updating the viewmodel.
Like this:

testViewModel.Data.trigger("change");
0
On

You are mixing stufs a bit. You dont need to define a Model nor trigger the change event. First initialize observable object:

var testViewModel = new kendo.observable({
    data: [
        { "Name": "Test1", "Amount": 100 },
        { "Name": "Test2", "Amount": 200 }
    ]
});

....bind it:

kendo.bind("#test", testViewModel.Data);

...change data:

testViewModel.data[0].set("Amount", 3000);

... HTML, check what data-template have and what script have:

<div id="test">
  <div data-bind="source: data" data-template="testTemplate"></div>
  <script id="testTemplate" type="text/x-kendo-template">
   <div>
        <span data-bind="text: Name"></span>
        <span data-bind="text: Amount"></span>
    </div>
  </script>
</div>

that's it!.

<div id="test">
  <div data-bind="source: data" data-template="testTemplate">
   
  </div>
  <script id="testTemplate" type="text/x-kendo-template">
   <div>
        <span data-bind="text: Name"></span>
        <span data-bind="text: Amount"></span>
    </div>
  </script>
</div>

<script>
   var testViewModel = new kendo.observable({
        data: [
            { "Name": "Test1", "Amount": 100 },
            { "Name": "Test2", "Amount": 200 }
        ]
    });
  
    kendo.bind($("#test"), testViewModel);
    
    testViewModel.data[0].set("Amount", 3000);

</script>

Working example: Observable binding

Check how to use observable object: Observable object