TinyMCE's isDirty method
I have a card-making web project. I have a tinyMCE textfield and a visual of the card. Upon changing the content of the tinyMCE editor I want to update the visual of the card to reflect the new text/changes.
TinyMCE comes with an IsDirty method:
if (tinyMCE.activeEditor.isDi开发者_StackOverflow社区rty())
alert("You must save your contents.");
What I don't understand is WHERE I would place this if statement to regularly check for it. I understand that JS is event driven and so it needs to be "called", do I call it every keypress?
You could add a global timeout function that every second or so (the interval is up to you) checks:
function updateCardIfDirty() {
if (tinyMCE.isDirty()) {
// rerender the card
}
}
setInterval(updateCardIfDirty, 2000); // check every 2 seconds.
A cleaner solution might be to check every time they make a change in the tinyMCE editor. This can be made possible by the onChange()
event tinyMCE provides, as follows:
tinyMCE.init({
...
setup : function(ed) {
ed.onChange.add(function(ed, l) {
// rerender the card
});
}
});
The downside of the first approach is that it will execute every 2 seconds, even if they dont edit the card for an hour. The downside of the second approach is that if they perform 10 edits in 1 second, it will rerender the card 10 times in that second.
So finally, let's try a third approach which gets the best of both worlds, and loses both disadvantages we mentioned:
tinyMCE.init({
...
setup : function(ed) {
ed.onChange.add(function(ed, l) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function(){ timeout=null; rerenderCard(); }, 1000);
});
}
});
I am currently trying to see how to fix TinyMCE in this regard. Outside of TinyMCE, the current cross browser solution is to use the OnTextChange DOM event that is supported by most of the current browsers. I test it today and it works really nice for non-keyboard right click cut/paste/delete and also keyboard changes. No Keyboard events necessary with the textchange event. (Note, it needs to be prepared in DOM, google the jquery.textchange.js plugin).
However, it doesn't work when TinyMCE is wrapping the textarea control. I am currently looking at the source and the plugins to see how to implement this textchange event.
精彩评论