Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent "with" binding from removing DOM elements (Knockout.js)

Knockouters,

I have come to rely on the with binding for establishing context nesting. while I like the way KO manipulates the DOM based on the state of the bound elements in some instances, sometime I just want the binding implications without the DOM removal.

Does anyone know if it is possible way to prevent the DOM manipulation on an individual element binding level?

Thanks, Vinney

like image 639
Vinney Kelly Avatar asked Jan 09 '13 18:01

Vinney Kelly


People also ask

What are the types of binding supported by knockout JS?

Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.

What is binding in knockout JS?

A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .

What is two way binding in knockout JS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.

What happens in visible binding?

When the parameter transforms into true-like value (such as boolean true,or nonnull object or array ), the binding removes yourElement. style. display value, making it visible. If this is an observable property, then the binding will update visibility every time the property changes.


1 Answers

Version 2.2+ of Knockout won't clear the DOM element when with is bound initially to an object (or other truthy value). Alternatively, you can use the withlight binding that I put together some time ago. It only will bind to an object (not an observable).

ko.bindingHandlers['withlight'] = {
    'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var bindingValue = valueAccessor();
        if (typeof bindingValue != 'object' || bindingValue === null)
            throw new Error('withlight must be used with an object');
        var innerContext = bindingContext['createChildContext'](bindingValue);
        ko.applyBindingsToDescendants(innerContext, element);
        return { 'controlsDescendantBindings': true };
    }
};
like image 96
Michael Best Avatar answered Oct 17 '22 12:10

Michael Best