简体   繁体   中英

KnockoutJS IF binding - keep DOM

The if binding removes DOM and stops executing inner data-bind attributes if the condition is false .

Is it possible to keep the DOM even when condition is false ? I just want to stop executing data-bind when condition is false but I do not wish to remove any DOM due to JQuery bindings etc.

I came with the following solution which basically delays knockout binding application until a condition is satisfied.

It does not remove binding when the condition becomes false but this is not necessary in my case.

ko.bindingHandlers['applyWhen'] = {
  init: function() {
    return { controlsDescendantBindings: true };
  },
  update: function(element, valueAccessor, allBindings, model, bindingContext) {
    if (!element.bindingApplied && Boolean(ko.unwrap(valueAccessor()))) {
      element.bindingApplied = true;
      ko.applyBindingsToDescendants(bindingContext, element);
    }
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM