Ad

Backbone: Uncaught TypeError: Cannot Read Property 'toJSON' Of Undefined

- 1 answer

I'm getting the follow error: "Uncaught TypeError: cannot read property 'toJSON' of undefined"

I bet is stupid mistake (granted doesn't help to focus the fact that my 2 year old daughter is with me), but here I am.

This is my code:

(function($){


  // Model:
  //-------

  var DirectoryItem = Backbone.Model.extend({
    defaults: function(){
        title: 'New Company'
    },

    initialize: function() {
        console.log(this.get('title'));    
    }

  });

  var Company1 = new DirectoryItem({title:'Company number 1'});

  // Collection:
  //------------

  var Directory = Backbone.Collection.extend({
    model: DirectoryItem,

    initialize: function() {
      console.log('New collection created...');         
    }

  });

  var directory = new Directory(Company1);

  // View:
  //------

  var DirectoryListView = Backbone.View.extend({

    el: $("#directoryView"),

    template: _.template($('#item-list-template').html()),

    initialize: function(){
        this.render();                
    },

    render: function () {
      this.$el.html(this.template(this.model.toJSON()));
      return this;
    }

  });

  var directoryListView = new DirectoryListView();

})(jQuery);

Someone can help me?

Thanks!

PD: probably you already noticed it but I'm new to Backbone

Edit: as a template I have this:

<script type="text/template" id="item-list-template">
    <li><%= title %></li>
</script>
Ad

Answer

First. You made a mistake on this line:

var directory = new Directory(Company1);

because of Directory collection expects an array as first argument but not scalar. So fix this to the following:

var directory = new Directory([Company1]);

Second. Chnage you DirectoryListView class to:

var DirectoryListView = Backbone.View.extend({

el: $("#directoryView"),

template: _.template($('#item-list-template').html()),

initialize: function(){
    this.render();                
},

render: function () {
  this.collection.each(function (model) {
      var html = this.template(model.toJSON());
      this.$el.append(html);
  }, this);

  return this;
}

Third. Change your directoryListView initialization to the following:

var directoryListView = new DirectoryListView({ collection: directory })
Ad
source: stackoverflow.com
Ad