Skip to content

@derickbailey /1-form.html
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.