Is there an alternative to the IValueConverter in Knockout js?

若如初见. 提交于 2020-01-13 07:05:12

问题


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

Is there something like:

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

Thanks in advance,

Arne Deruwe


回答1:


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

Edit:

And your html would look like:

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


来源:https://stackoverflow.com/questions/12671126/is-there-an-alternative-to-the-ivalueconverter-in-knockout-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!