【问题标题】:Knockout observables: Manually apply extendersKnockout observables:手动应用扩展器
【发布时间】:2014-03-17 00:30:25
【问题描述】:

我编写了一个扩展器,当用户模糊日期输入字段时格式化日期(换句话说,valueUpdate 不是'afterkeydown')。

但问题是,由于某些其他原因,我需要在每次按下按键后更新值,但我不希望在用户模糊之前应用格式。

有没有办法将扩展器设置为“手动”,可以这么说,然后手动调用扩展器,如下所示:

someObservable.applyExtenders(); //applies all extenders

someObservable.applyExtenders(['formatDate']);  //applies a list of extenders

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    您不必像手动应用扩展程序那样复杂。

    一个更简单的解决方案是创建一个自定义绑定,在用户键入日期时验证日期,然后在触发更改事件时格式化日期。

    Fiddle.

    (function(ko) {
    
        ko.bindingHandlers.dateValid = {
            // set up bindings on the init function
            // you can use afterkeydown to get the value as the user types it in
            // then you can use the change event to do the formatting
            init: function(elem, valueAccessor, allBindings, vm, context) {
                function formatDate() {
                    alert('Im getting formatted!');   
                }
                // add the other bindings to the node
                ko.applyBindingsToNode(elem, { 
                    value: valueAccessor(), // the observable
                    valueUpdate: 'afterkeydown', 
                    event: { change: formatDate } // this will format on change not keydown
                });
            },
            update: function(elem, valueAccessor, allBindings, vm, context) {
                var val = ko.unwrap(valueAccessor());
                // do validation or whatever needs to be done as the value updates here
            }
        };    
    
        function ViewModel() {
            this.date = ko.observable('11/22/63');
        }
    
        ko.applyBindings(new ViewModel());
    
    }(ko));
    

    【讨论】:

    • 我爱淘汰赛!这正是我正在寻找的!我编写了许多自定义绑定,但我从未考虑过ko.applyBindingsToNode。非常感谢。
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 2014-01-25
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多