Skip to content

Instantly share code, notes, and snippets.

@wilfreddenton
Last active June 1, 2016 23:48
Show Gist options
  • Save wilfreddenton/94351ee7766b2cb0da50 to your computer and use it in GitHub Desktop.
Save wilfreddenton/94351ee7766b2cb0da50 to your computer and use it in GitHub Desktop.
var Ripples = function (initialState, setStateCallback) {
this.state = initialState;
this.events = {};
this.eventTargets = {};
this.setStateCallback = setStateCallback;
for (var key in this.state) {
var eventName = 'ripple' + key;
this.events[eventName] = new Event(eventName);
this.eventTargets[eventName] = [];
}
}
Ripples.prototype.setState = function (newState) {
for (var key in newState) {
if (newState.hasOwnProperty(key)) {
var eventName = 'ripple' + key;
ripples.state[key] = newState[key];
this.eventTargets[eventName].forEach(function (ele) {
ele.dispatchEvent(this.events[eventName]);
}.bind(this));
}
}
if (typeof this.setStateCallback === 'function')
this.setStateCallback();
}
Ripples.prototype.ripple = function (stateKeys, elements, reaction) {
if (!Array.isArray(stateKeys)) stateKeys = [stateKeys];
if (!Array.isArray(elements)) elements = [elements];
stateKeys.forEach(function (key) {
var eventName = 'ripple' + key;
elements.forEach(function (element) {
element.addEventListener(eventName, reaction);
this.eventTargets[eventName].push(element);
}.bind(this));
}.bind(this));
}
Ripples.prototype.calm = function (stateKeys, elements, reaction) {
if (!Array.isArray(stateKeys)) stateKeys = [stateKeys];
if (!Array.isArray(elements)) elements = [elements];
stateKeys.forEach(function (key) {
var eventName = 'ripple' + key;
elements.forEach(function (element) {
element.removeEventListener(eventName, reaction);
var i = this.eventTargets[eventName].indexOf(element);
this.eventTargets[eventName].splice(i, 1);
}.bind(this));
}.bind(this));
}
Ripples.prototype.render = function (template) {
if (typeof template[0] === 'string') template = [template];
var docFrag = document.createDocumentFragment();
template.forEach(function (subTemp) {
var tag = subTemp[0], params = subTemp[1], children = subTemp[2];
var element = document.createElement(tag);
for (var key in params) {
var param = params[key];
if (typeof param === 'object' && param && !Array.isArray(param)) {
for (var name in param)
element[key][name] = param[name];
} else { element[key] = param; }
}
if (Array.isArray(children)) {
var childFrag = this.render(children);
element.appendChild(childFrag);
} else { element.innerHTML = children; }
docFrag.appendChild(element);
}.bind(this));
return docFrag;
}
@wilfreddenton
Copy link
Author

To see how to use Ripples check out this implementation of TodoMVC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment