Skip to content

Instantly share code, notes, and snippets.

@dergachev
Last active December 18, 2015 05:29
Show Gist options
  • Save dergachev/5733254 to your computer and use it in GitHub Desktop.
Save dergachev/5733254 to your computer and use it in GitHub Desktop.
I made this gist in the course of experimenting with backbone.js.
jQuery(function ($) {
var Resource = Backbone.Model.extend( { url: null } ),
ResourceList = Backbone.Collection.extend( { model: Resource } );
var AppView = Backbone.View.extend({
el: $("#backbone"),
initialize: function(initialData) {
this.resources = new ResourceList(null, {view: this});
this.newResource = new Resource;
this.listenTo(this.newResource, 'change', this.render);
this.listenTo(this.resources, 'add', this.addResourceLi);
this.resources.add(initialData);
},
events: {
"change": "changedName",
"click #add-resource": "handleAddResource",
},
addResourceLi: function(model) {
console.log(this);
var link = $("<a/>")
.attr('href', model.get('url'))
.text(model.get('url'))
.appendTo(this.$el.find('#resources'))
.wrap('<li />');
},
render: function() {
var newName = this.newResource.get('url');
this.$el.find('#resource-url').val(newName);
this.$el.find('button').text("Add Resource: " + newName);
},
changedName: function() {
this.newResource.set('url', this.$el.find('#resource-url').val());
},
handleAddResource: function () {
var resource_url = this.newResource.get('url');
var resource_model = new Resource({url:resource_url});
this.resources.add(resource_model);
this.newResource.set('url','');
}
});
var data = _.map([
"https://github.com/thomasdavis/thomasdavis.github.com/blob/master/examples/backbone-101/index.html",
"http://backbonejs.org/#Collection-constructor",
"http://tutorialzine.com/2013/04/services-chooser-backbone-js/",
"http://stackoverflow.com/questions/9216443/backbone-js-splitting-a-model-between-views",
"http://stackoverflow.com/questions/4074636/can-i-bind-form-inputs-to-models-in-backbone-js-without-manually-tracking-blur-e"
], function(d) { return {url: d};});
var appview = new AppView(data);
});
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
<script src="backbone-tutorial.js"></script>
</head>
<body>
<h1>Backbone Tutorial</h1>
<p>Play with this list of resources, and then view source.</p>
<div id="backbone">
URL: <input id="resource-url" name="resource-url" style="width:80%;"/> <button id="add-resource">Add</button>
<ul id="resources">
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment