Reputation: 14426
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");
}
}
Upvotes: 2
Views: 243
Reputation: 17564
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
Upvotes: 1
Reputation: 575
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
Upvotes: 2