SteveSanderson / knockout-es5

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

Mutating a property can create a dependency on it #3

Closed mbest closed 11 years ago

mbest commented 11 years ago

Usually it's best to not mutate observables in a computed, but if you do so, you generally don't also want a dependency on that observable. If you simply write to the property, it's not a problem, but if you first read it, you'll get a dependency. Example: this.quantity += 1; or this.myArray.remove(item);. With this plugin, it's a but harder to avoid the dependency. You'd have to use ko.getObservable(someModel, 'email').peek() to access the value without creating a dependency. The above examples would become this.quantity = ko.getObservable(this, 'quantity').peek() + 1; and ko.getObservable(this, 'myArray').remove(item);

SteveSanderson commented 11 years ago

I agree, though I'm not sure it's really any different with KO-ES5 than plain KO, apart from the extra syntax.

In general, if a developer mutates an observable from within a computed, it's not always clear what they are trying to do. If some common usage pattern leads to big problems (like race conditions or memory leaks) then I'd be very keen to help guide people away from it, but otherwise I'm not too worried about this.

If you have changes in mind, please let me know! I'll close this issue now because I'm not sure what other action to take on it, but let me know if you think there is something we should do.

Thanks.

mbest commented 11 years ago

Your suggestion in #2 about using a modified property name to access the observable would help solve the problem described here also.