Last active
December 26, 2015 12:59
-
-
Save billychan/7155216 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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