0

I am getting an error when calling the fetch function.

Undefined is not a function Error in Backbone js 

var models = Backbone.Model.extend({
  userId: function() {
    return this.get('userId');
  },
  id: function() {
    return this.get('id');
  },
  body: function() {
    return this.get('body');
  }
});
//Collections
var todolistStore = Backbone.Collection.extend({
  url: function() {
    return 'https://jsonplaceholder.typicode.com/posts'
  },
  model: models,
  parse: function(response) {
    return response;
  }
});
todolistStore.fetch();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>

8
  • 1
    Looks like you need to instantiate first: var myStore = new todolistStore(); myStore.fetch();
    – user5734311
    Commented Dec 18, 2017 at 13:11
  • @ChrisG Still not working Commented Dec 18, 2017 at 13:20
  • 1
    You're using old versions of underscore and backbone. When I use current versions instead, the errors disappear.
    – user5734311
    Commented Dec 18, 2017 at 13:30
  • You don't need to provide an id function as Backbone already provides an id property that's linked to the id attribute. Commented Dec 19, 2017 at 4:53
  • Also, the parse function is useless if the data only passes through. Commented Dec 19, 2017 at 4:57

1 Answer 1

5

There are a couple of problems. I'm building off of @ChrisG 's answer.

  1. You need to instantiate a collection. Here's what my code:

    var Model = Backbone.Model.extend({
        userId: function() {
            return this.get('userId');
        },
        id: function() {
            return this.get('id');
        },
        body: function() {
            return this.get('body');
        }
    });
    
    //Collections
    var TodoListStore = Backbone.Collection.extend({
        url: function() {
            return 'https://jsonplaceholder.typicode.com/posts'
        },
        model: Model,
        parse: function(response) {
            return response;
        }
    });
    
    var todolistStore = new TodoListStore();
    todolistStore.fetch();
    
  2. I updated the version of Underscore and Backbone

    https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.