Skip to content

Instantly share code, notes, and snippets.

@hay
Last active October 7, 2015 09:38
Show Gist options
  • Save hay/3144721 to your computer and use it in GitHub Desktop.
Save hay/3144721 to your computer and use it in GitHub Desktop.
Learn Javascript MVC: create a todo list using Stapes.js in less than 100 lines code (part 2)
<script type="text/html" id="template">
<ul>
{{#todos}}
<li data-id="{{id}}">
<input type="checkbox" class="remove" />
{{text}}
</li>
{{/todos}}
</ul>
<p>{{size}} todos left</p>
</script>
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"></script>
var listTemplate = Handlebars.compile( $("#template").html() );
var listTemplate = Handlebars.compile( $("#template").html() );
var TodosModel = Stapes.subclass();
var InputView = Stapes.subclass({
constructor : function( model ) {
this.model = model;
this.$el = $("#inputform");
this.$input = this.$el.find("input");
this.bindEventHandlers();
},
bindEventHandlers : function() {
this.$el.on('submit', function(e) {
e.preventDefault();
this.model.push({
"text" : this.$input.val()
});
this.$input.val('');
}.bind(this));
}
});
var ListView = Stapes.subclass({
constructor : function( model ) {
this.model = model;
this.$el = $("#todos");
this.template = listTemplate;
},
render : function() {
var html = this.template({
size : this.model.size(),
todos : this.model.getAllAsArray()
});
this.$el.html( html );
}
});
var TodosController = Stapes.subclass({
constructor : function() {
this.model = new TodosModel();
this.listView = new ListView( this.model )
this.inputView = new InputView( this.model );
this.model.on('change', function() {
this.listView.render();
}, this);
}
});
var controller = new TodosController();
var html = this.template({
size : this.model.size(),
todos : this.model.getAllAsArray()
});
<p>{{size}} todos left</p>
{{#todos}}
<li data-id="{{id}}">
<input type="checkbox" class="remove" />
{{text}}
</li>
{{/todos}}
bindEventHandlers : function() {
this.$el.on('click', '.remove', function(e) {
var id = $(e.target).parents("li").data('id');
this.model.remove(id);
}.bind(this));
},
this.bindEventHandlers();
var TodosModel = Stapes.subclass({
constructor : function() {
if (window.localStorage.todos) {
var todos = JSON.parse( window.localStorage.todos );
this.set( todos );
}
},
save : function() {
window.localStorage.todos = JSON.stringify( this.getAll() );
}
});
this.model = new TodosModel();
this.listView = new ListView( this.model )
this.inputView = new InputView( this.model );
this.model.on('change', function() {
this.listView.render();
this.model.save();
}, this);
this.listView.render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment