Skip to content

Instantly share code, notes, and snippets.

@theotherzach
Last active January 3, 2016 18:19
Show Gist options
  • Save theotherzach/8501387 to your computer and use it in GitHub Desktop.
Save theotherzach/8501387 to your computer and use it in GitHub Desktop.
A Pen by Zach.
<input id="zb-input" required value="" placeholder="Enter your name">
<br />
<h4>Current Name: <span id="zb-output"></span>
</h4>
var app = app || {};
(function(){
"use strict";
var inputView = {
template: document.getElementById('zb-input'),
model: app.userModel,
};
function handleInput(e) {
this.model.name = e.srcElement.value;
}
inputView.template.addEventListener("keyup", handleInput.bind(inputView));
app.inputView = inputView;
})();
var app = app || {};
(function(){
"use strict";
var outputView = {
template: document.getElementById('zb-output'),
model: app.userModel,
render: function() {
this.template.innerText = this.model.name;
},
};
outputView.model.onNameChange(outputView.render.bind(outputView));
app.outputView = outputView;
})();
var app = app || {};
(function(){
"use strict";
var _name = "default value";
var listeners = [];
var userModel = {
onNameChange: function(fun) {
listeners.push(fun);
},
notifyListeners: function(value, model) {
listeners.forEach(function(listener) {
listener.call(this, value, model);
});
},
};
Object.defineProperties(userModel, {
name: {
get: function() {
return _name;
},
set: function(name) {
_name = name;
this.notifyListeners(name, userModel);
},
},
});
app.userModel= userModel;
})();
@theotherzach
Copy link
Author

Note that unlike Backbone models, we can trigger change events by setting an attribute via =

https://gist.github.com/theotherzach/8501387#file-user_model-js-L22-L32
https://gist.github.com/theotherzach/8501387#file-input_view-js-L14-L16

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