JSFiddle - React, Tailwind, and code Playground
by IPWright83
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>
<div class="inverse-toggle" data-bind="toggleInverse: isInversed"></div>
CSS
.inverse-toggle {
color: #33bdde;
border-bottom: thin solid #33bdde;
cursor: pointer;
-webkit-user-select: none;
display: inline-block;
}
JavaScript
ko.bindingHandlers.toggleInverse = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
// Determine the initial value of the binding
var value = valueAccessor();
// Create a span for the text and register a click handler
$(element).on("click", function(d) {
value(!value());
});
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever any observables/computeds that are accessed change
// Update the DOM element based on the supplied values here.
var value = valueAccessor();
var isInversed = ko.unwrap(value);
var text = isInversed ? "is not" : "is";
// Update the label for the span
var span = $(element, ".isInversed").text(text);
}
};
var vm = {
isInversed: ko.observable(true)
};
ko.applyBindings(vm);