Hmm, that's not extending the text
binding, you're overwriting it.
First things first, note that currently the text
binding is extremely simple. Taken from the source:
ko.bindingHandlers['text'] = {
'init': function() {
// Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
// It should also make things faster, as we no longer have to consider whether the text node might be bindable.
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor) {
ko.utils.setTextContent(element, valueAccessor());
}
};
The actual functionality is offloaded to setTextContent
, which handles cross-browser setting of, well, text content.
If you want to have a binding that does things similar to text
, only with some added features, the easiest way probably is to create a custom binding handler yourself that utilizes setTextContent
. For example:
ko.bindingHandlers['myText'] = {
'init': function() {
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()), txt = '';
if (value !== null && typeof value == "object") {
txt = value['text'];
if (!!value['required']) { txt += "!!!"; }
} else {
txt = value;
}
ko.utils.setTextContent(element, txt);
}
};
ko.applyBindings({ testProperty: "test text 1234" });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<span data-bind="myText: { text: testProperty, required: true }"></span>
<br>
<span data-bind="myText: { text: testProperty, required: false }"></span>
<br>
<span data-bind="myText: testProperty"></span>