Question

I have a DIV, which I use as a binding root node when applying ko bindings this way:

ko.applyBindings(viewModel, document.getElementById('myContainerDiv'));

I have a generic post method defined for every viewmodel type, with common ajax handling, etc. In this method I would like to access the binding root node, so in this case the DIV with 'myContainerDiv', for example to be able to use some loading spinner on it or so.

I've checked the documentation but only found the "inverse" operation (ko.dataFor). What I would like is something like this pseudo code:

BaseViewModel.prototype.post = function(url, options) {
    // this refers to my actual viewmodel

    var element = ....... get the binding root node for 'this'
    element.showLoading();
    ....
    // ajax stuff
    .... 
    element.hideLoading();
};

EDIT: I'm using the jQuery.blockUI plugin for showing/hiding loading panels above elements, so it's not just about binding a loading DIV's visible property to an observable.

Was it helpful?

Solution

I managed to implement a custom binding for the jQuery.blockUI plugin, and bound my container DIV with that to my model's IsLoading property. During the AJAX callback I set the IsLoading observable to true.

<div data-bind="blockUI: IsLoading">
    ...
</div>

And the binding handler:

ko.bindingHandlers.blockUI = {
    update: function (element, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        if (value)
            $(element).block();
        else 
            $(element).unblock();
    }
};

Thank you for the base idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top