Backbone js
Method map, with mustache js
by erick
HTML
<script src="https://raw.github.com/documentcloud/underscore/master/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="https://raw.github.com/janl/mustache.js/master/mustache.js"></script>
<script type="text/template" id="humans_list_tpl">
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>{{#humans}}
<tr>
<td>{{firstName}}</td>
<td>{{lastName}}</td>
</tr>
{{/humans}}
</tbody>
</table>
<a id="delete" href="#">Delete All</a>
<a id="save" href="#">Save All (see navigator console)</a>
</script>
<div id="humans_list"></div>
JavaScript
window.Models = {};
window.Collections = {};
window.Views = {};
Backbone.idCounter = 0;
Backbone.sync = function(method, model, options) {
console.log("-->", method);
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
var type = methodMap[method];
if(model.model) { //This is a collection
} else { //This is a model
switch (type) {
case "POST": //CREATE
Backbone.idCounter+=1;
model.set("id", Backbone.idCounter );
options.success(model);
break;
case "PUT": //UPDATE
options.success(model);
break;
case "GET": //FETCH
options.success(model);
break;
case "DELETE": //DESTROY
delete model;
options.success(model);
break;
default:
console.log ("???");
}
}
};
$(function (){
Views.HumansList = Backbone.View.extend({
el : $("#humans_list"),
initialize : function () {
this.template = $("#humans_list_tpl").html();
},
render : function () {
var renderedContent = Mustache.to_html(this.template, {humans : this.collection.toJSON()} );
this.$el.html(renderedContent);
},
events : {
"click #delete" : "deleteAll",
"click #save" : "saveAll"
},
deleteAll : function() {
this.collection.each(function(model) {
model.destroy({success:function(){}});
});
this.render();
},
saveAll : function() {
this.collection.each(function(model) {
model.save({},{success:function(){ console.log("save : ",model.get("id"));}});
});
}
});
Models.Human = Backbone.Model.extend({
...