In one of our projects, we were creating a web site using ASP.NET single page application with knockout.js. We had to add TinyMCE HTML editor in one of my pages. It took some time to make it work. Add a binding handler for tinyMce using Knockout. Please see the code below:
ko.bindingHandlers.tinymce = {
init: function (element, valueAccessor, allBindingsAccessor, context) {
var options = allBindingsAccessor().tinymceOptions || {};
var modelValue = valueAccessor();
var value = ko.utils.unwrapObservable(valueAccessor());
var el = $(element)
options.theme = "advanced";
options.theme_advanced_buttons1 = "bold,italic,underline,separator," +
"strikethrough,justifyleft,justifycenter,justifyright, " +
"justifyfull,separator,bullist,numlist,undo,redo,link,unlink";
options.theme_advanced_buttons2 = "outdent,indent," +
"separator,forecolor,backcolor,emoticons,separator,formatselect";
options.theme_advanced_buttons3 = "";
options.setup = function (ed) {
ed.onChange.add(function (ed, l) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(l.content);
}
});
};
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
setTimeout(function () { $(element).tinymce().remove() }, 0)
});
setTimeout(function () {
$(element).tinymce(options);
}, 1000);
el.html(value);
},
update: function (element, valueAccessor, allBindingsAccessor, context) {
var el = $(element)
var value = ko.utils.unwrapObservable(valueAccessor());
var id = el.attr('id')
if (id !== undefined) {
$(el).tinymce();
var tinyM = tinyMCE.getInstanceById(id);
if (tinyM !== undefined) {
var content = tinyM.getContent({ format: 'raw' })
if (content !== value) {
el.html(value);
}
}
}
}
};
Now, you can bind any text area using data-bind
of knockout and don’t forget to assign id to the element, e.g., id=”txtPublished”
.
<textarea data-bind="tinymce: publishNotes"
id="txtPublished" style="height: 150px;
width: 550px;"></textarea>