我只是试图摆弄淘汰赛提供的样本并尝试绑定两个视图模型,这是代码,我遇到了第二个视图模型的问题:
<div class='liveExample1'>
<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>
</div>
<div class='liveExample'>
<form data-bind="submit: addItem">
New item:
<input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p>Your items:</p>
<select multiple="multiple" width="50" data-bind="options: items"> </select>
</form>
</div>
我的观点模型是:
<script type="text/javascript">
// Here's my data model
$(document).ready(function () {
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function () {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"), $("#liveExample1")[0]); // This makes Knockout get to work?
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
}
}.bind(this); // Ensure that "this" is always this view model
};
ko.applyBindings(new SimpleListModel(["Alpha", "Beta", "Gamma"]), $("#liveExample")[0]);
});
如何解决,“此”问题
答案 0 :(得分:1)