knockout.js输入框事件更改 - 传递旧值 [英] knockout.js input box event change - passes old value

查看:379
本文介绍了knockout.js输入框事件更改 - 传递旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用knockout.js将更改事件绑定添加到输入框时,会在触发事件时将旧值传递给change函数。我可以通过使用模糊来解决这个问题。这是预期的行为吗?是否使用change事件来获取旧值,然后使用普通选择器从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.

jsFiddle示例

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆