Question

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:

  1. the events that call the functions to populate the views are being bound to the collection of models
  2. when I fetch the model data the collection is getting updated with the data from the server
  3. however, the reset event bound to the collection does not fire

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;
Was it helpful?

Solution 2

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

OTHER TIPS

You're probably getting an empty jQuery selector returned by the el: $("#contactsapp") configuration in your view.

http://lostechies.com/derickbailey/2011/11/09/backbone-js-object-literals-views-events-jquery-and-el/

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top