1

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

Arne Deruwe
  • 1,100
  • 2
  • 11
  • 25

1 Answers1

4

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' } " />
Community
  • 1
  • 1
Sethi
  • 1,378
  • 8
  • 14
  • just what I needed, thanks! One small thing, you should remove the closing bracket under the else if because you have one too many. Thanks again for the fast response! – Arne Deruwe Oct 01 '12 at 11:28
  • Glad I could help! Sorry, yes, I've actually added a bracket as I think it's best to enclose yours blocks like `if(...) { ... }` rather than `if(...) ...` as it improves readability and makes it easier to add code later – Sethi Oct 01 '12 at 12:02