Created
June 27, 2015 04:06
-
-
Save sher/23ed544e29804ad24a11 to your computer and use it in GitHub Desktop.
Styled React component mixin with reference counting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _mount(style, styles) { | |
for (var i = 0; i < styles.length; i++) { | |
if (style == styles[i].getAttribute('href')) { | |
styles[i].dataset.refc++; | |
return; | |
} | |
} | |
var newStyle = document.createElement('link'); | |
newStyle.setAttribute('rel', 'stylesheet'); | |
newStyle.setAttribute('type', 'text/css'); | |
newStyle.setAttribute('href', style); | |
newStyle.dataset.refc = 1; | |
document.head.appendChild(newStyle); | |
} | |
function _unmount(style, styles) { | |
var existingStyle; | |
for (var i = 0; i < styles.length; i++) { | |
if (style == styles[i].getAttribute('href')) { | |
styles[i].dataset.refc--; | |
existingStyle = styles[i]; | |
break; | |
} | |
} | |
if (existingStyle.dataset.refc <= 0) { | |
document.head.removeChild(existingStyle); | |
} | |
} | |
var StyleMixin = { | |
componentWillMount() { | |
if (this.style) { | |
var links = document.head.getElementsByTagName('link'); | |
var styles = []; | |
for (var i = 0; i < links.length; i++) { | |
if (links[i].getAttribute('rel') == 'stylesheet') { | |
styles.push(links[i]); | |
} | |
} | |
if (this.style.constructor === Array) { | |
this.style.forEach(function (style) { | |
_mount(style, styles); | |
}) | |
} | |
else { | |
_mount(this.style, styles); | |
} | |
} | |
}, | |
componentWillUnmount() { | |
if (this.style) { | |
var links = document.head.getElementsByTagName('link'); | |
var styles = []; | |
for (var i = 0; i < links.length; i++) { | |
if (links[i].getAttribute('rel') == 'stylesheet') { | |
styles.push(links[i]); | |
} | |
} | |
if (this.style.constructor === Array) { | |
this.style.forEach(function (style) { | |
_unmount(style, styles); | |
}) | |
} | |
else { | |
_unmount(this.style, styles); | |
} | |
} | |
} | |
} | |
export default StyleMixin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment