Is there an alternative to the IValueConverter in

2019-04-15 01:46发布

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

标签: knockout.js
1条回答
贼婆χ
2楼-- · 2019-04-15 02:09

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' } " />
查看更多
登录 后发表回答