javascript - 如何让 Knockout JS 在按键上进行数据绑定(bind)而不是失去焦点?

标签 javascript knockout.js

knockout js 这个例子因此,当您编辑字段并按 TAB 时, View 模型数据以及字段下方的文本都会更新。

如何更改此代码,以便每次按键都更新 View 模型数据?

alt text

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

来自 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.

关于javascript - 如何让 Knockout JS 在按键上进行数据绑定(bind)而不是失去焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386311/

相关文章:

javascript - 根据同一对象的 'sibling' 可观察到的 knockout

javascript - 按 dom 的顺序优雅地制作重叠的 DIV

javascript - 使用 self.port.on 时,Firefox 内容脚本中的变量未更新

javascript - 从 Canvas 读取时出现 IE9 安全错误(非跨域)

php - 关于实时搜索领域的安全问题

javascript - knockout table : Highlight a Table Row

backbone.js 和/或 knockout.js 中的 AngularJS 示例

javascript - jQuery .each 循环不循环,但当你 console.log 时却循环?

javascript - 从 JSFiddle 发出复制代码

javascript - 从 knockout 应用绑定(bind)中排除 DOM 元素?