Skip to content

Instantly share code, notes, and snippets.

@zfedoran
Last active March 31, 2017 20:42
Show Gist options
  • Save zfedoran/2d65b44b9d917aacb5f0 to your computer and use it in GitHub Desktop.
Save zfedoran/2d65b44b9d917aacb5f0 to your computer and use it in GitHub Desktop.
Vu.js - Tiny Front-end Framework
// Vu.js v0.9000.1 Library
/* (Please don't use this, created as a joke) */
/* Live Example: https://jsfiddle.net/ya76bu7b/3/ */
class Vu {
constructor(config) {
this.$el = document.querySelector(config.el);
this.$template = _.template(config.template || this.$el.outerHTML);
this.$options = _.extend({ data: {} }, config);
this.$data = _.extend({}, this.$options.data);
this.init();
}
init() {
// Watch for data changes
this.traverse(this.$data, this.watch.bind(this));
// Link first level of $data down to the vm
_.each(_.keys(this.$data), this.link.bind(this));
// Render the HTML
this.render();
if (this.$options.created) {
this.$options.created.call(this);
}
}
traverse(obj, func) {
for (var prop in obj) {
const val = obj[prop];
if (val !== null && typeof (val) === 'object') {
this.traverse(val, func);
}
func.apply(this, [obj, prop, val]);
}
}
watch(obj, prop, val) {
const hidden = {}; hidden[prop] = val;
Object.defineProperty(obj, prop, {
get: () => { return hidden[prop] },
set: (newVal) => {
hidden[prop] = newVal; this.render();
}
});
}
link(prop) {
Object.defineProperty(this, prop, {
get: () => { return this.$data[prop] },
set: (newVal) => { this.$data[prop] = newVal; }
});
}
render() {
this.$el.innerHTML = this.$template(this.$data);
if (this.$options.ready) {
this.$options.ready.call(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment