Knockout observables:手动应用扩展器

时间:2014-03-16 02:54:28

标签: javascript knockout.js

我编写了一个扩展程序,用于格式化用户模糊日期输入字段的日期(换句话说,valueUpdate &#39; afterkeydown&#39;)。< / p>

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

有没有办法将扩展器设置为&#34;手动&#34;,可以这么说,然后用这样的东西手动调用扩展器:

someObservable.applyExtenders(); //applies all extenders

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

1 个答案:

答案 0 :(得分: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));