2

I currently have all my labels looking something like this:

<label data-bind="css: { notdone: FirstName.isModified() && !FirstName.isValid(),
       done: FirstName.isModified() && FirstName.isValid() }">FirstName</label>

I would like to create a custom binding to extract out that duplication across the labels without reimplementing the CSS binding.

Is it possible for me to use the CSS binding within my custom binding?

If not then i will be reinventing the wheel in order to get rid of some duplication like so:

ko.bindingHandlers.validationLabel =
{
  update: (element, valueAccessor) =>
  {
      var value = valueAccessor();
      var isModified = value.isModified();
      var isValid = value.isValid();

      $(element).removeClass("done notdone");

      if (!isModified)
          return;

      $(element).addClass(isValid ? "done" : "notdone");
  }
}
4imble
  • 13,979
  • 15
  • 70
  • 125
  • 1
    After reading the post, I leaned toward using a [template](http://knockoutjs.com/documentation/template-binding.html) for the labels. Assuming `FirstName` is an observable, pass it along with the label you want to use into the template and use dynamic class version of the css binding. See [fiddle](http://jsfiddle.net/origineil/eDLKB/). – Origineil Apr 08 '14 at 20:11

2 Answers2

2

You can call the built in bindings from within your own. Something like this should work in your update method to replace your jQuery code:

ko.bindingHandlers.css.update(element, function() {
    return { done: isValid, notdone: !isValid }
});

Related question with more details: Can I create a custom binding that uses other bindings in knockout.js

Community
  • 1
  • 1
Charlie
  • 575
  • 2
  • 7
1

The correct approach is to use ko.applyBindingsToNode

var notValid = ko.computed(function() {
   return !isValid();
});
ko.applyBindingsToNode(element, { done: isValid, notdone: notValid });

This way it will hook up the bindings correctly, not just call the update method. It should be called from the init function of your custom binding. Not each update

Anders
  • 17,306
  • 10
  • 76
  • 144