Created
July 30, 2016 00:52
-
-
Save krambuhl/6e1b701603cef0677a40e3f17e19b624 to your computer and use it in GitHub Desktop.
elm'ish architecture in javascript
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 Table(el) { | |
this.cacheElements(el); | |
this.defineUpdates(); | |
// MODEL | |
this.state = {}; | |
// define initial view state | |
this.setState({ | |
activeRow: 0 | |
}); | |
} | |
Table.prototype = { | |
// cache any children elements for use later | |
cacheElements: function(el) { | |
this.el = el; | |
this.rows = this.el.querySelectorAll('tr'); | |
}, | |
// SIGNALS / EVENTS | |
// define events that update the view state | |
defineUpdates: function() { | |
var self = this; | |
this.rows.forEach(function(row, index) { | |
row.addEventListener('click', function(ev) { | |
self.setState({ | |
activeRow: index | |
}); | |
}); | |
}); | |
}, | |
// VIEW UPDATES | |
// define how changes in the state data | |
// should effect the view DOM | |
setState: function(state) { | |
// create a copy of the last state for reference | |
this.lastState = Object.assign({}, this.state); | |
// update the state property | |
Object.assign(this.state, state); | |
// only make updates if activeRow is defined | |
if (state.activeRow !== undefined && state.activeRow !== this.lastState.activeRow) { | |
this.rows[this.state.activeRow].classList.add('is-active'); | |
if (this.lastState.activeRow !== undefined) { | |
this.rows[this.lastState.activeRow].classList.remove('is-active'); | |
} | |
} | |
} | |
} | |
document.querySelectorAll('table').forEach(function(table) { | |
new Table(table); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment