我是Knockout的新手,我正在学习MVVM的工作原理。这是我的代码的代码片段。
$(function () {
var viewModel = {
name: ko.observable("Bob"),
changeName: function () {
this.name("Steve");
},
nameVisible: ko.observable(true);
};
ko.applyBindings(viewModel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>
Name:
<input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'" />
<input type="checkbox" data-bind="checked: nameVisible" />
<p>Hello, <span data-bind='text: name, visible: nameVisible'></span>
</p>
<button data-bind='click: changeName'>Change Name</button>
我正在尝试将View数据绑定到ViewModel。选中复选框时,应显示输入字段中的文本。单击该按钮时,还应将输入字段更新为“Steve”(仅当选中该复选框时)。出了什么问题?
答案 0 :(得分:2)
语法错误。应该是:
$(function () {
var viewModel = {
name: ko.observable("Bob"),
changeName: function () {
this.name("Steve");
},
nameVisible: ko.observable(true)
};
ko.applyBindings(viewModel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>
Name:
<input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'" />
<input type="checkbox" data-bind="checked: nameVisible" />
<p>Hello, <span data-bind='text: name, visible: nameVisible'></span>
</p>
<button data-bind='click: changeName'>Change Name</button>
在nameVisible: ko.observable(true)
始终打开开发者控制台。