JSFiddle - React, Tailwind, and code Playground
by lookitstony
HTML
I am attempting to share the same property that will be bound to the text boxes but I only want the value to show if the textbox is enabled. I am trying to create a handler so i do not have to do a bunch of observables or functions for each field like this.
<div>
<input type="radio" name="item" value="1" data-bind="checked:Selected" /> Item 1 <input type="text" data-bind="enable: IsEnabled('1'), enableValue: Price" />
</div>
<div>
<input type="radio" name="item" value="2" data-bind="checked:Selected" /> Item 2 <input type="text" data-bind="enable: IsEnabled('2'), enableValue: Price" />
</div>
<div>
<input type="radio" name="item" value="3" data-bind="checked:Selected" /> Item 3 <input type="text" data-bind="enable: IsEnabled('3'), enableValue: Price" />
</div>
<div>
<input type="radio" name="item" value="4" data-bind="checked:Selected" /> Item 4 <input type="text" data-bind="enable: IsEnabled('4'), enableValue: Price" />
</div>
Selected Price: <span data-bind="text: Price"></span>
<pre data-bind="text: ko.toJSON($data, 0, 3)"></pre>
JavaScript
(function (ko, handlers, unwrap, extend) {
"use strict";
extend(handlers, {
enableValue: {
init: function (element, valueAccessor, allBindings) {
var showValue = ko.computed({
read: function(){
if (unwrap(allBindings().enable)) {
return unwrap(valueAccessor());
} else {
return '';
}
},
write: valueAccessor()
});
ko.applyBindingsToNode(element, { value: showValue });
}
}
});
}(ko, ko.bindingHandlers, ko.utils.unwrapObservable, ko.utils.extend));
var vm = {
Selected: ko.observable('1'),
Price: ko.observable(12),
IsEnabled: function(item){
var selected = this.Selected();
return (selected == item)
}
}
ko.applyBindings(vm);