首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >剔除可观测值:手动应用扩展器

剔除可观测值:手动应用扩展器
EN

Stack Overflow用户
提问于 2014-03-16 02:54:28
回答 1查看 186关注 0票数 1

我编写了一个扩展程序,在用户模糊日期输入字段时格式化日期(换句话说,valueUpdate不是“后置键”)。

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

是否有一种方法可以将扩展程序设置为“手动”,也就是说,然后用如下方式手动调用扩展程序:

代码语言:javascript
复制
someObservable.applyExtenders(); //applies all extenders

代码语言:javascript
复制
someObservable.applyExtenders(['formatDate']);  //applies a list of extenders
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-16 16:25:04

您不必做一些像手动应用扩展器这样复杂的事情。

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

小提琴。

代码语言:javascript
复制
(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));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22432420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档