2
votes

This post: Knockout: valueAccessor vs viewModel on custom binding handlers? makes the following statement about how the viewModel observables are bound within a custom binding handler: "Any observable that has its value accessed will create a dependency."

How do I access a value from the observable X on the viewModel inside a custom binding handler without creating a dependency that makes the custom binding handler to update if X is later changed?

I made a Fiddle that showcases this. The line viewModel.xxx(); creates a dependency to the "xxx" observable.

http://jsfiddle.net/hhw4a/5/

1
If you are using KO 2.3+, then you can do viewModel.xxx.peek() as well - RP Niemeyer
That's an even better solution that works without need of extra code. - Adrian Rosca

1 Answers

1
votes

Short answer: you can't.

Best workaround you have available, afaik: create a plain vanilla JavaScript property, and reference that. Something like this:

function Vm(){
    this.aOb = ko.observable('a value');
    this.a = this.aOb();
}

Now you may reference a in your custom bindings, and changes to aOb will not cause your binding to re-fire.

And if you want to always keep a in sync with aOb, you can use subscribe:

function Vm(){
    this.aOb = ko.observable('a value');
    this.a = this.aOb();

    this.aOb.subscribe(function(newVal){
       this.a = newVal;
    }.bind(this));
}