public
Last active

progressive enhancement with backbone

  • Download Gist
1-form.html
HTML
1 2 3
<form id="foo">
Name: <input id="name"><button id="say">Say My Name!</button>
</form>
2-sayname.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
FooView = Backbone.View.extend({
events: {
"change #name": "setName",
"click #say": "sayName"
},
 
setName: function(e){
var name = $(e.currentTarget).val();
this.model.set({name: name});
},
 
sayName: function(e){
e.preventDefault();
var name = this.model.get("name");
alert("Hello " + name);
},
 
render: function(){
// do some rendering here, for when this is just running javascript
}
});
 
$(function(){
var model = new MyModel();
var view = new FooView({
model: model,
el: $("#foo")
});
});
3-list.html
HTML
1 2 3 4 5 6
<ul id="user-list">
<li data-id="1">Bob
<li data-id="2">Mary
<li data-id="3">Frank
<li data-id="4">Jane
</ul>
4-list.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
User = Backbone.Model.extend({});
 
UserCollection = Backbone.Collection.extend({
model: User
});
 
UserListView = Backbone.View.extend({
attachToView: function(){
this.el = $("#user-list");
self = this;
this.$("li").each(function(index){
var userEl = $(this);
var id = userEl.attr("data-id");
var user = self.collection.get(id);
new UserView({
model: user,
el: userEl
});
});
}
});
 
UserView = Backbone.View.extend({
initialize: function(){
this.model.bind("change:name", this.updateName, this);
},
 
updateName: function(model, val){
this.el.text(val);
}
});
 
$(function(){
var userData = [
{id: 1, name: "Bob"},
{id: 2, name: "Mary"},
{id: 3, name: "Frank"},
{id: 4, name: "Jane"},
];
var userList = new UserCollection(userData);
var userListView = new UserListView({collection: userList});
userListView.attachToView();
 
userList.get(1).set({name: "No Longer Bob"});
 
});
5-pushstate.js
JavaScript
1
Backbone.history.start({pushState: true});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.