Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

- Use a collection to populate Documents in #index

- Use event binding to refresh the Edit view via Document changes
  • Loading branch information...
commit 11a542e9e82f371580ee291bde13daef03dfb623 1 parent ad95932
James Yu authored committed
View
1  config/assets.yml
@@ -7,6 +7,7 @@ javascripts:
- public/javascripts/backbone.js
- public/javascripts/application.js
- public/javascripts/jquery.dotimeout.js
+ - public/javascripts/models/*.js
- public/javascripts/**/*.js
stylesheets:
View
1  public/javascripts/application.js
@@ -1,6 +1,7 @@
var App = {
Views: {},
Controllers: {},
+ Collections: {},
init: function() {
new App.Controllers.Documents();
Backbone.history.start();
View
4 public/javascripts/collections/documents.js
@@ -0,0 +1,4 @@
+App.Collections.Documents = Backbone.Collection.extend({
+ model: Document,
+ url: '/documents'
+});
View
11 public/javascripts/controllers/documents.js
@@ -19,11 +19,12 @@ App.Controllers.Documents = Backbone.Controller.extend({
},
index: function() {
- $.getJSON('/documents', function(data) {
- if(data) {
- var documents = _(data).map(function(i) { return new Document(i); });
- new App.Views.Index({ documents: documents });
- } else {
+ var documents = new App.Collections.Documents();
+ documents.fetch({
+ success: function() {
+ new App.Views.Index({ collection: documents });
+ },
+ error: function() {
new Error({ message: "Error loading documents." });
}
});
View
9 public/javascripts/views/edit.js
@@ -4,6 +4,8 @@ App.Views.Edit = Backbone.View.extend({
},
initialize: function() {
+ _.bindAll(this, 'render');
+ this.model.bind('change', this.render);
this.render();
},
@@ -14,11 +16,6 @@ App.Views.Edit = Backbone.View.extend({
this.model.save({ title: this.$('[name=title]').val(), body: this.$('[name=body]').val() }, {
success: function(model, resp) {
new App.Views.Notice({ message: msg });
-
- self.model = model;
- self.render();
- self.delegateEvents();
-
Backbone.history.saveLocation('documents/' + model.id);
},
error: function() {
@@ -46,5 +43,7 @@ App.Views.Edit = Backbone.View.extend({
$('#app').html(this.el);
this.$('[name=title]').val(this.model.get('title')); // use val, for security reasons
+
+ this.delegateEvents();
}
});
View
5 public/javascripts/views/index.js
@@ -1,13 +1,12 @@
App.Views.Index = Backbone.View.extend({
initialize: function() {
- this.documents = this.options.documents;
this.render();
},
render: function() {
- if(this.documents.length > 0) {
+ if(this.collection.models.length > 0) {
var out = "<h3><a href='#new'>Create New</a></h3><ul>";
- _(this.documents).each(function(item) {
+ this.collection.each(function(item) {
out += "<li><a href='#documents/" + item.id + "'>" + item.escape('title') + "</a></li>";
});
out += "</ul>";
Please sign in to comment.
Something went wrong with that request. Please try again.