使用knockout js绑定更新html元素

时间:2014-02-18 06:35:30

标签: knockout.js jquery-mobile-listview

我想用knockout js绑定更新ui。我能够更新列表,但更改不会反映在ui中。我收到了以下错误:

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

以下是我的代码: 当我检查数组的长度时,警报显示数组已更新但我希望更改也反映在ui中。

<!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>

1 个答案:

答案 0 :(得分:0)

ko.applyBindings()函数只能调用一次。从那时起,您对viewmodel中可观察对象所做的每一个更改都将自动反映在该人中。

只需取消对init();功能中AddPerson()功能的调用,只需从其他地方调用一次即可解决问题

相关问题