Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created September 26, 2011 20:48
Show Gist options
  • Save mxriverlynn/1243356 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1243356 to your computer and use it in GitHub Desktop.
progressive enhancement with backbone
<form id="foo">
Name: <input id="name"><button id="say">Say My Name!</button>
</form>
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")
});
});
<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>
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"});
});
Backbone.history.start({pushState: true});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment