Knockout点击绑定奇怪的行为 [英] Knockout click binding strange behavior
本文介绍了Knockout点击绑定奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试获得基本的Knockout点击绑定设置,如下例所示:
Trying to get basic Knockout click binding set up, as per the example below:
<button id="btn-a" class="btn" data-bind="css: {'btn-primary':mode() == 'manual'}, click: $root.mode('manual')">Manual</button>
<button id="btn-b" class="btn" data-bind="css: {'btn-primary':mode() == 'automatic'}, click: $root.mode('automatic')">Automatic</button>
<label>MODE: </label><span data-bind="text:mode()"></span>
<script>
$(function () {
var TestModel = function() {
var self = this;
this.mode = ko.observable('manual');
};
var testModel = new TestModel();
window.testModel = testModel;
ko.applyBindings(testModel);
});
小提琴: http: //jsfiddle.net/aq85wk65/
Fiddle: http://jsfiddle.net/aq85wk65/
然而,遇到两个问题:
- 绑定导致
mode()
值开始为
'automatic',即使我们将其显式初始化为'手册'。 - 每当点击一个按钮时,javascript控制台会显示:
- The binding causes the
mode()
value to start out as 'automatic', even though we explicitly initialize it to 'manual'. - Whenever a button is clicked, the javascript console shows:
Uncaught TypeError:h.apply不是函数
Uncaught TypeError: h.apply is not a function
推荐答案
你需要包装你的点击功能中的处理程序:
You need to wrap your click handlers in function:
http:// jsfiddle。 net / aq85wk65 / 1 /
<button id="btn-a" class="btn" data-bind="css: {'btn-primary':mode() == 'manual'}, click: function(){$root.mode('manual')}">Manual</button>
参见 http://knockoutjs.com/documentation/click-binding.html
这篇关于Knockout点击绑定奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文