为什么下面的代码没有按预期工作?当我只调用一个ko.applyBindings方法时,它可以工作。 我们可以在一个页面中调用多个ko.applyBindings方法吗?
<body>
<form id="form1" runat="server">
<div>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
The name is <span data-bind="text: personName"></span>
</div>
</form>
</body>
<script type="text/javascript">
var myViewModel = {
personName: 'Bob',
personAge: 123
};
var ViewModel=function(first, last)
{
this.firstName=ko.observable(first);
this.lastName=ko.observable(last);
this.fullName=ko.pureComputed(function()
{
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(myViewModel);
ko.applyBindings(new ViewModel("Hello", "World"));
</script>
答案 0 :(得分:2)
是的,你可以。但是您需要使用要应用绑定的元素调用ko.applyBindings
。以下是从您发布的代码中借用的示例:
HTML:
<div id="model1">
<p>First name: <input type="text" data-bind="value: firstName" /></p>
<p>Last name: <input type="text" data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2> </div>
<div id="model2">
The name is <span data-bind="text: personName"></span>,
age is <span data-bind="text: personAge"></span>
</div>
JavaScript的:
var myViewModel = {
personName: 'Bob',
personAge: 123
};
var ViewModel = function(first, last) {
this.firstName=ko.observable(first);
this.lastName=ko.observable(last);
this.fullName=ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(myViewModel, document.getElementById('model2'));
ko.applyBindings(new ViewModel("Hello", "World"), document.getElementById('model1'));
注意我将ko.pureComputed
更改为ko.computed
,因为我使用的淘汰赛3运行时没有pureComputed。你使用的是扩展吗?
JSFiddle:http://jsfiddle.net/krpqzwqd/