Reputation: 23
I am new to Backbone and started by working through the Todos example. After that I created a new version of the example, for Contacts rather than Todos, that uses a Ruby on Rails web app and and it's associated REST API rather than localstorage for persistence. After making the modifications I am able to successfully have the Backbone app update the Rails app but I cannot get the Backbone views to render the data that the Backbone app receives from the Rails REST API. I have stepped through the code in the debugger and can see that:
Can anybody point me to what might be causing the reset event to not fire? My code is below:
Collection:
var ContactsList = Backbone.Collection.extend({
model: Contact,
url: 'http://localhost:3000/contacts.json',
});
var Contacts = new ContactsList;
AppView:
var AppView = Backbone.View.extend({
el: $("#contactapp"),
events: {
"keypress #new-contact": "createOnEnter"
},
initialize: function() {
this.input = this.$("#new-contact");
Contacts.bind('add', this.addOne, this);
Contacts.bind('reset', this.addAll, this);
Contacts.bind('all', this.render, this);
Contacts.fetch();
},
addOne: function(contact) {
var view = new ContactView({model: contact});
this.$("#contact-list").append(view.render().el);
},
addAll: function() {
Contacts.each(this.addOne);
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!this.input.val()) return;
Contacts.create({first_name: this.input.val()});
this.input.val('');
},
});
var App = new AppView;
Upvotes: 0
Views: 543
Reputation: 23
After much debugging I found that the bound reset
event was not being fired because I was using an old version of backbone.js. In the version I was using the refresh
event was being fired not the reset
event. Once I upgraded to the newer version of backbone.js the reset
event fired
Upvotes: 0
Reputation: 72878
You're probably getting an empty jQuery selector returned by the el: $("#contactsapp")
configuration in your view.
don't use jQuery selectors as object literal values. with Backbone's view, you can just provide the selector string:
el: "#contactsapp"
but this is a bad idea anyways. you should let the view render it's own el, and use other code to populate the "#contactsapp" element with the view:
$(function(){
view = new AppView();
view.render();
$("#contacts").html(view.el);
});
See the above link for more info.
Upvotes: 0