Knockout js中是否可以替代IValueConverter? [英] Is there an alternative to the IValueConverter in Knockout js?

查看:62
本文介绍了Knockout js中是否可以替代IValueConverter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道您可以使用Compute Observables.它们确实非常适合复杂的属性,但是IMO并不是您在Silverlight中拥有的IValueConverters的理想替代品. 在我当前的项目中,我有多个日期选择器.现在,我必须为每个日期创建一个额外的可计算观察值,因为我希望格式能够正常工作.因此,如果我有5个日期即10个属性,那么在Silverlight中,您将有5个日期和1个通用dateconverter.

First of all, I know you can use Computed observables. They are really great for complex properties, but IMO are not a worthy replacement for the IValueConverters you have in Silverlight. In my current project, I have multiple datepickers. Right now, I have to create an extra computed observable for each date, because I want the formatting to work. So If I have 5 dates that's 10 properties, where in Silverlight you would have 5 dates and 1 generic dateconverter.

它可以工作,但是代码不是很干净..更不用说在将验证应用于这些日期时遇到的问题了.

It works, but it's not very clean code.. Not to mention the issues you get when applying validation to these dates..

有没有类似的东西

<input type="text" data-bind="value: TestProperty" data-converter="MyTextConverter" />

或者有什么其他选择不能让我创建双重属性吗?

Or is there any alternative to this which doesn't let me create double properties?

预先感谢

Arne Deruwe

Arne Deruwe

推荐答案

您正在寻找自定义绑定.请参见此处以获取良好指南

You're looking at a prime use for a custom-binding. See here for a good guide

ko.bindingHandlers.dateConverter = {
  init: function (element, valueAccessor, allBindingsAccessor) {
    var underlyingObservable = valueAccessor();
    var options = allBindingsAccessor().dateConverterOptions
                    || { /* set defaults here */ };

    var interceptor = ko.computed({
      read: function() {
        return underlyingObservable();
      },

      write: function(newValue) {
        var current = underlyingObservable(),
            convertedDate;

        /* do some kind of conversion here, using the 'options' object passed */

        if (convertedDate !== current) {
          underlyingObservable(convertedDate);
        }
        else if (newValue !== current.toString()) {
          underlyingObservable.valueHasMutated();
        }
      }
    });

      ko.applyBindingsToNode(element, { value: interceptor });
  }
};

此处修改的拦截器代码

Interceptor code modified from here

您的html如下所示:

And your html would look like:

<input type="text"
       data-bind="dateConverter: TestProperty,
                  dateConverterOptions: { format: 'dd/mm/yyyy', anotherOption: 'example' } " />

这篇关于Knockout js中是否可以替代IValueConverter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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