0

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();
    1

    2 Answers 2

    0

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

    Sign up to request clarification or add additional context in comments.

    Comments

    0

    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

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.