Skip to content

Instantly share code, notes, and snippets.

@NOtherDev
Created November 5, 2014 08:35
Show Gist options
  • Save NOtherDev/9e713cfd68d6da9a174a to your computer and use it in GitHub Desktop.
Save NOtherDev/9e713cfd68d6da9a174a to your computer and use it in GitHub Desktop.
ShareJS attachSelect
// code that allows attaching ShareJS to HTML <select> fields
sharejs.Doc.prototype.attachSelect = function (innerElem, ctx) {
var i;
var rawValue = innerElem.value;
var elem = {
get value () {
return rawValue;
},
set value (v) {
rawValue = v;
innerElem.value = v;
}
};
var eventFuncs = ['addEventListener', 'attachEvent', 'removeEventListener', 'detachEvent'];
for (i = 0; i < eventFuncs.length; ++i) {
if (innerElem[eventFuncs[i]]) {
elem[eventFuncs[i]] = innerElem[eventFuncs[i]].bind(innerElem);
}
}
var changeHandler = function () {
rawValue = innerElem.value;
innerElem.dispatchEvent(new Event('textInput'));
};
var delayedChangeHandler = function () {
setTimeout(changeHandler, 0);
};
var addEvent = function (event, handler) {
if (innerElem.addEventListener) {
innerElem.addEventListener(event, handler, false);
} else {
innerElem.attachEvent('on' + event, handler);
}
};
var removeEvent = function (event, handler) {
if (innerElem.removeEventListener) {
innerElem.removeEventListener(event, handler, false);
} else {
innerElem.detachEvent('on' + event, handler);
}
};
addEvent('change', changeHandler);
addEvent('keyup', changeHandler);
addEvent('keydown', delayedChangeHandler);
if (!ctx) {
ctx = this.createContext();
}
ctx.detach = function () {
removeEvent('change', changeHandler);
removeEvent('keyup', changeHandler);
removeEvent('keydown', delayedChangeHandler);
};
return this.attachTextarea(elem, ctx);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment