Skip to content

Instantly share code, notes, and snippets.

@billychan
Last active December 26, 2015 12:59
Show Gist options
  • Save billychan/7155216 to your computer and use it in GitHub Desktop.
Save billychan/7155216 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="http://documentcloud.github.io/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.io/backbone/backbone-min.js"></script>
<title>Backbone load existing DOM elements</title>
</head>
<body>
<p>This is a working version. All models and collection can be created from DOM elments without extra data.
<ul id="user-list">
<li data-id="1">Bob-Dom
<li data-id="2">Mary-Dom
<li data-id="3">Frank-Dom
<li data-id="4">Jane-Dom
</ul>
</body>
</html>
User = Backbone.Model.extend({});
UserCollection = Backbone.Collection.extend({
model: User
});
UserListView = Backbone.View.extend({
attachToView: function(){
this.el = $("#user-list");
this.el.find('li').each(function(index){
var userEl = $(this);
var id = userEl.attr("data-id");
var user = new User({id: 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 = [];
var userList = new UserCollection(userData);
var userListView = new UserListView();
userListView.attachToView();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment