Last active
April 30, 2019 06:41
-
-
Save bcherny/19954506283377fb44be to your computer and use it in GitHub Desktop.
simple mvc
This file contains hidden or 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
// model | |
function Model () { | |
this._state = {} | |
return this | |
} | |
Model.prototype.get = function (key) { | |
return this._state[key] | |
} | |
Model.prototype.set = function (key, value) { | |
this._state[key] = value | |
return this | |
} | |
// view | |
function View (container, html) { | |
this.container = container | |
this.html = html | |
return this | |
} | |
View.prototype.template = function (model) { | |
var _html = this.html | |
Object | |
.keys(model) | |
.forEach(function (key) { | |
_html = _html.replace(new Regexp('({{\s?' + key + '\s?}})', 'g'), model[key]) | |
}) | |
return $(_html) | |
} | |
View.prototype.render = function (model) { | |
this | |
.template(model) | |
.appendTo(this.container) | |
} | |
// controller | |
var model = new Model() | |
.set('foo', 10) | |
.set('bar', 20) | |
// demo | |
var html = '<div class="{{ foo }}">{{ bar }}</div>' | |
new View($('#container'), html) | |
.render(model) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment