Knockout.js 输入框事件更改 - 传递旧值 [英] knockout.js input box event change - passes old value
问题描述
当使用knockout.js 将更改事件绑定添加到输入框时,旧值会在事件触发时传递给更改函数.我可以通过使用模糊来解决这个问题.这是预期的行为吗?使用更改事件具有旧值然后使用普通选择器从 dom 获取值的想法是什么?这似乎违反直觉.
When adding a change event binding to an input box using knockout.js the old value is passed to the change function when the event is fired. I can work around this by using blur. Is this the intended behavior? Is the idea to use the change event to have the old value and then use a normal selector to get the value from the dom? It seems counter intuitive.
JavaScript
----------
var data = {
saved_value:"1",
value_changed: function(data){
alert(data.saved_value());
}
};
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
HTML
----
Current Value:<span data-bind="text:saved_value"></span><br/>
<input data-bind="event:{change:value_changed},value:saved_value"></input>
推荐答案
尝试使用文本和值绑定:
Try using the text and value bindings:
Current Value:<span data-bind="text: saved_value"></span><br/>
<input data-bind="value: saved_value"></input>
并将 JavaScript 更改为:
And change the JavaScript to this:
var data = {
saved_value: "1"
};
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
这是一个相关的 jsFiddle:http://jsfiddle.net/6zmJs/
Here's an associated jsFiddle: http://jsfiddle.net/6zmJs/
如果您想在更新时alert()
saved_value
的值,您可以使用 ko.computed
或 viewModel.saved_value.subscribe(function(value) { alert(value); });
-- 尽管这些并不是唯一的方法.
If you want to alert()
the value of saved_value
when it is updated you could use ko.computed
or viewModel.saved_value.subscribe(function(value) { alert(value); });
-- although those aren't the only ways to do this.
这篇关于Knockout.js 输入框事件更改 - 传递旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!