SteveSanderson / knockout-es5

Knockout.js meets ECMAScript 5 properties
158 stars 39 forks source link

Need to be able to unregister tracked property #18

Closed jrsearles closed 9 years ago

jrsearles commented 10 years ago

I have a case where i have a property on a model that is a plain observable. The model is then run through ko.track. Later on as the model is processed it needs to be modified with a custom computed property in some cases. Setting the property will have it wrapped in the original observable and exposed to consumers as an observable instead of a plain property. I'm looking for a way to unregister the property or the entire object from the internal registry so that it can be run through ko.track again with the updated observable.

kring commented 9 years ago

I had the exact same situation. It's a bit of a hack, but I found a workaround.

Just to set the stage... Initially, you define a tracked property like this:

this.foo = 1;
ko.track(this, ['foo']);

Then later you want to do something like this:

var whatever = 2;
ko.defineProperty(this, 'foo', {
    get : function() {
        return whatever;
    },
    set : function(value) {
        whatever = value;
    }
});

The result of that ko.defineProperty won't be an observable property as we want. Instead, the value of this.foo after the call will be a plain, old, non-ES5 knockout.computed. This strikes me as a bug in knockout-es5. It should at least throw, right?

In any case, the workaround is to do this just before the defineProperty:

delete this.__knockoutObservables.foo;

Definitely a hack, but it works for me. Maybe it'll help you, too.