Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Created October 10, 2016 20:45
Show Gist options
  • Save LeeCheneler/3c3dd5e4dc1e319167b1d42551c0ae05 to your computer and use it in GitHub Desktop.
Save LeeCheneler/3c3dd5e4dc1e319167b1d42551c0ae05 to your computer and use it in GitHub Desktop.
twoway binding for innerText (textContent in firefox) property on DOM element
/*
*
* innertext binding - twoway binding between dom and knockout observable
*
*/
// Helper class
var KOInnerTextHelper = (typeof KOInnerTextHelper !== 'undefined') ?
KOInnerTextHelper :
function () {
this.getInnerText = function (element) {
// Not all browsers support innterText...
if (element.innerText) {
return element.innerText;
}
// Firefox uses textContent
return element.textContent;
};
this.setInnerText = function (element, text) {
// Not all browsers support innterText...
if (element.innerText) {
element.innerText = text;
}
// Firefox uses textContent
element.textContent = text;
}
};
// Binding methods
var KOInnerTextBindingInit = (typeof KOInnerTextBindingInit !== "undefined") ?
KOInnerTextBindingInit :
function (element, valueAccessor) {
var observable = valueAccessor();
var helper = new KOInnerTextHelper();
element.addEventListener("DOMSubtreeModified", function () {
observable(helper.getInnerText(element));
});
};
var KOInnerTextBindingUpdate = (typeof KOInnerTextBindingUpdate !== "undefined") ?
KOInnerTextBindingUpdate :
function (element, valueAccessor) {
// Might not be observable, safer to call ko.unwrap(...) to get actual value
var value = ko.unwrap(valueAccessor());
var helper = new EasyInnerTextHelper();
helper.setInnerText(element, value);
}
// Create binding
ko.bindingHandlers.innerText = {
init: KOInnerTextBindingInit,
update: KOInnerTextBindingUpdate
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment