Pregunta

I've looked at this: http://knockoutjs.com/documentation/extenders.html

The issue is that I'm using fromJs to create my view model, so my observerables already exist. I would think I could do the following to add an extender:

var data = result.Data;
if (!window.vmRealTimeActivity) {
    window.vmRealTimeActivity = ko.mapping.fromJS(data, mappingKeys);
    ko.applyBindings(vmRealTimeActivity, $('#second-btm')[0]);
} else {
    ko.mapping.fromJS(data, vmRealTimeActivity);
}

vmRealTimeActivity.MyExistingObservable.extend({ numeric: null });
vmRealTimeActivity.MyExistingObservable(9999);  // doesn't call numeric extender

My extender gets called the first time the extender is attached, but not after trying to change the value.

I read another SO post that stated that .extend() creates a new observerable so you have to do this, but this doesn't work either:

vmRealTimeActivity.MyExistingObservable = vmRealTimeActivity.MyExistingObservable.extend({ numeric: null });

In addition to not calling my formatter a second time, the value starts coming back NaN.

How do I attach an extender the proper way to an existing observable?

¿Fue útil?

Solución

Since you are using the mapping plugin, you could specify a create callback. If you add the following to the existing mappingKeys, it would probably work (I don't know your exact mapping, so you might need to change bits here and there):

'MyExistingObservable': {
    create: function(options) {
        return new ko.observable(options.data).extend({ numeric: null });
    }
}

This result in an extended observable upon mapping from yor data.

Here's a jsFiddle with a working example (vm1) and your current non-working example (vm2) for comparison

Otros consejos

The above answer is correct, but for anyone interested, I found the simpler approach is to just create your view models client side and use fromJs to refresh them rather than both create and refresh them. You can then apply the answer here to support adding extend to both your parent and child view models: Map JSON data to Knockout observableArray with specific view model type

With either approach you will have to create additional mappings.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top