如何让 Knockout JS 在按键上进行数据绑定而不是失去焦点? [英] How can I get Knockout JS to data-bind on keypress instead of lost-focus?

查看:25
本文介绍了如何让 Knockout JS 在按键上进行数据绑定而不是失去焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个

<块引用>

附加参数

  • 值更新

    如果您的绑定还包含一个名为 valueUpdate 的参数,则此定义 KO 应该使用哪个浏览器事件来检测更改.这以下字符串值是最常用的选项:

    • "change" (默认) - 当用户更新你的视图模型将焦点移动到不同的控件,或者在元素,在任何更改后立即

    • "keyup" - 当用户释放一个键时更新你的视图模型

    • "keypress" - 当用户输入一个钥匙.与 keyup 不同,这会在用户持有密钥时重复更新下

    • "afterkeydown" - 用户一出现就更新你的视图模型开始输入字符.这是通过捕获浏览器的keydown 事件并异步处理该事件.

在这些选项中,如果你想,afterkeydown"是最好的选择使您的视图模型实时更新.

This example of knockout js works so when you edit a field and press TAB, the viewmodel data and hence the text below the fields is updated.

How can I change this code so that the viewmodel data is updated every keypress?

<!doctype html>
<html>
    <title>knockout js</title>
    <head>
        <script type="text/javascript" src="js/knockout-1.1.1.debug.js"></script>
        <script type="text/javascript">
        window.onload= function() {

            var viewModel = {
                firstName : ko.observable("Jim"),
                lastName : ko.observable("Smith")
            };
            viewModel.fullName = ko.dependentObservable(function () {
                return viewModel.firstName() + " " + viewModel.lastName();
            });

            ko.applyBindings(viewModel);
       }
        </script>
    </head>
    <body>
        <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>
    </body>
</html>

解决方案

<body>
        <p>First name: <input data-bind="value: firstName, valueUpdate: 'afterkeydown'" /></p>
        <p>Last name: <input data-bind="value: lastName, valueUpdate: 'afterkeydown'" /></p>
        <h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
</body>

From the documentation

Additional parameters

  • valueUpdate

    If your binding also includes a parameter called valueUpdate, this defines which browser event KO should use to detect changes. The following string values are the most commonly useful choices:

    • "change" (default) - updates your view model when the user moves the focus to a different control, or in the case of elements, immediately after any change

    • "keyup" - updates your view model when the user releases a key

    • "keypress" - updates your view model when the user has typed a key. Unlike keyup, this updates repeatedly while the user holds a key down

    • "afterkeydown" - updates your view model as soon as the user begins typing a character. This works by catching the browser’s keydown event and handling the event asynchronously.

Of these options, "afterkeydown" is the best choice if you want to keep your view model updated in real-time.

这篇关于如何让 Knockout JS 在按键上进行数据绑定而不是失去焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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