0
votes

So I created a rails api using rails-api gem. And I put my backbone code in the default public/index.html. I tried the json link and returns json, it's just a model called 'entry' with a single field called 'content' along with some default rails fields. But the backbone code doesn't work, could you spot any problem with this? I am just trying to show the list of records from the returned json.

// Models
window.Entry = Backbone.Model.extend();
window.EntryCollection = Backbone.Collection.extend({
    model:Entry,
    url:"http://localhost:3000/entries"
});

// Views
window.EntryListView = Backbone.View.extend({
    tagName:'ul',
    initialize:function () {
        this.model.bind("reset", this.render, this);
    },
    render:function (eventName) {
        _.each(this.model.models, function (entry) {
            $(this.el).append("
  • " + entry.get("content") + "
  • "); }, this); return this; } }); // Router var AppRouter = Backbone.Router.extend({ routes:{ "":"list" }, list:function () { this.entryList = new EntryCollection(); this.entryListView = new EntryListView({model:this.entryList}); this.entryList.fetch(); $('#entries').html(this.entryListView.render().el); } }); var app = new AppRouter(); Backbone.history.start();
    2
    see this link = github.com/documentcloud/backbone and try thisDipak Panchal

    2 Answers

    0
    votes

    Can You check perhaps if /entries return 'results' node? Perhaps You forgot to ActiveRecord::Base.include_root_in_json = false in Rails?

    0
    votes

    In your AppRouter code, you have this line:

    this.entryListView = new EntryListView({model:this.entryList});
    

    However, entryList is a Collection, not a Model, so you have to define it like this:

    this.entryListView = new EntryListView({collection:this.entryList});
    

    Similarly, in your EntryListView code, you have:

    this.model.bind("reset", this.render, this);
    
    ...
    
    _.each(this.model.models, function (entry) {
    

    which should become:

    this.collection.bind("reset", this.render, this);
    
    ...
    
    _.each(this.collection.models, function (entry) {
    

    I'm not sure if that is everything, but it's the only thing that is immediately apparent to me.

    edit: added add'l change to this.model reference