0

In my code I first use registerEventHandler to use the jquery currency plugin so it maps "€ 123,00" to 123,00.

ko.bindingHandlers.currency = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).currency && $(element).currency("destroy");
        });
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($(element).asNumber({ region: 'nl-BE' }));
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        /*snip snip*/
    }
};

Now when elsewhere I subscribe to the change event as follows, I still receive the string rather then the number:

self.initial.subscribe(function(newValue) {
    console.log("newValue", newValue);
}, null, "change");

When setting a breakpoint at the registerEventHandler for "change", I notice it gets hit after my subscription.

What am I missing?

Boris Callens
  • 90,659
  • 85
  • 207
  • 305
  • 1
    I would instead do this as a computed, either in a binding handler like you have made or with a extender – Anders Jan 27 '14 at 14:56
  • @Anders, could you elaborate? Currently the eventhandler makes sure this is registered for all currency fields across the entire site. The subscription is for a single field on which I need to apply some logic on change. – Boris Callens Jan 27 '14 at 15:05

1 Answers1

1

You can do this with a computed either in a binding handler or as a extender

As binding handler

http://jsfiddle.net/mJ7Vw/

ko.bindingHandlers.currency = {
    init: function(element, accessor) {
        var computed = ko.computed(function() {
            return ko.unwrap(accessor()) +" do custom formating";
        });
        ko.applyBindingsToNode(element, { text: computed });
    }
};

As extender

http://jsfiddle.net/mJ7Vw/1/

ko.extenders.currency = function(observable) {
    return ko.computed(function() {
            return observable() +" do custom formating";
        });
};
Anders
  • 17,306
  • 10
  • 76
  • 144
  • Think I'm missing a peace of information. The currency plugin works on the element itself. I can't just hand it a string after which it returns me the computed value – Boris Callens Jan 28 '14 at 09:57
  • 1
    Sounds like a dumb plugin if it needs a element, a currency formatter should not have dependecies to the DOM, are you sure there isnt a overloaded function that lets you just format a string? You can use a dummy element if you want. Or check out https://github.com/jquery/globalize its the standard for Client side globalization. – Anders Jan 28 '14 at 10:16