Question

I want to update ui with knockout js binding. I am able to update list but changes are not getting reflected in ui. I am getting following error :

Uncaught Error: You cannot apply bindings multiple times to the same element.

Following is my code: When I check the length of array, alert shows array is updated but I want the changes to be reflected in ui also.

<!DOCTYPE html>
<html>
<head>
<script src="js/knockout-3.0.0.js"></script>
<script>

var Person = [ {
    name : "qwe qwe",
    number : 123123123
}, {
    name : "asd asd",
    number : 999999999
} ];

var myVM = function() {
    this.persons = ko.observableArray(Person);
}

function init() {   
alert(Person.length);
    ko.applyBindings(new myVM());   
}

function AddPerson()
{
PushToArray(Person,"name","123");
init();
}

function PushToArray(array, var1, var2) {
    array.push({
        name : var1,
        number : var2
    });
}
</script>

</head>
<body onload="init()">
            <div>
                <button onclick="AddPerson()">Add</button>              
                    <div data-bind="foreach:persons">
                        <p data-bind="text:name"> </p>
                    </div>                      
            </div>      
</body>
</html>
Was it helpful?

Solution

The ko.applyBindings() function has to be called only once. From then every change you make to the observable objects in the viewmodel will be automatically reflected in the guy.

Just remove the call to the init(); function inside your AddPerson() function and call it only once from somewhere else and that should fix the problem

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top