Shaci
Shaci

Reputation: 316

knockout.js unwrapObservable function

I find todomvc examples - http://todomvc.com/ When i watch knockout version i find this code (in https://github.com/tastejs/todomvc/blob/gh-pages/architecture-examples/knockoutjs/js/app.js):

// wrapper to hasFocus that also selects text and applies focus async
ko.bindingHandlers.selectAndFocus = {
    init: function (element, valueAccessor, allBindingsAccessor, bindingContext) {
        ko.bindingHandlers.hasFocus.init(element, valueAccessor, allBindingsAccessor, bindingContext);
        ko.utils.registerEventHandler(element, 'focus', function () {
            element.focus();
        });
    },
    update: function (element, valueAccessor) {
        ko.utils.unwrapObservable(valueAccessor()); // for dependency
        // ensure that element is visible before trying to focus
        setTimeout(function () {
            ko.bindingHandlers.hasFocus.update(element, valueAccessor);
        }, 0);
    }
};

I know what do ko.utils.unwrapObservable(valueAccessor()); function, but what it do in this code? We don't use returned value.

Upvotes: 0

Views: 720

Answers (2)

ddio
ddio

Reputation: 26

Knockout set up a dependency chain base on what observable you used in current iteration.

To make your update function be executed again when a observable A changed, you need to directly or indirectly access to A.

Say, if your bindHandlers use the following syntax:

<div data-bind="selectAndFocus: A"></div>

you need to use one of the following js code:

valueAccessor();  // directly access
ko.utils.unwrapObservable( valueAccessor ); // directly access

If your bindHandler use the following syntax:

<div data-bind="selectAndFocus: { arg0: A, arg1: B }"></div>

You need to use the following js to make update handler depends on A

// no dependency injection in this line
var va = valueAccessor();  

// directly access
va.arg0();  
ko.utils.unwrapObservable( va.arg0 );

See How dependency tracking works for detailed information.

Upvotes: 1

John Earles
John Earles

Reputation: 7194

Knockout sets up publish-subscribe dependencies for observables evaluated in bindings, so that the bindings can update if the observable changes. The code is just using unwrapObservable as a safe way to evaluate the valueAccessor passed to the binding, capturing the dependency.

Upvotes: 0

Related Questions