JSFiddle - React, Tailwind, and code Playground
by bmh_ca
HTML
<script src="https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.debug.js"></script>
<script src="https://raw.github.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js"></script>
<div>Output (should be "Ehh Beh Seh"): <strong data-bind='customBinding: abc'></strong></div>
<div>Text (should also be "Ehh Beh Seh"): <em data-bind='text: abc'></em></div>
JavaScript
extender = function(target, opts) {
var result = ko.computed({
read: function() {
return target() + " is Ehh Beh Seh!"
},
write: function(new_val) {
alert("got a new value! " + new_val);
}
});
result(target());
return result;
};
ko.bindingHandlers.customBinding = {
init: function(element, valueAccessor, allBindings, viewModel) {
// change valueAccessor (an observable) to be extended
$(element).text(valueAccessor()());
$.each(viewModel, function (index, observable) { // _.any to early out is preferable.
if (observable === valueAccessor()) {
viewModel[index] = observable.extend(extender);
}
});
},
update: function(element, valueAccessor, allBindings, viewModel) {
$(element).text(valueAccessor()());
}
};
// elsewhere
prototype_data = {
abc: "abc"
};
bindings = ko.mapping.fromJS(prototype_data);
ko.applyBindings(bindings);