Search code examples
backbone.jsmodelundefinedrequiretodomvc

TodoMVC with backbone and require cannot fetch from server


There are a number of questions like this. I have not found an answer.

Using the example TodoMVC with backbone.js and require.js, I want to fetch from the server not from localstorage.

I have an url that return a proper json collection, where the models is like this:

{"string1": "foo", "string2":"bar", "somefloat":0}

In my model (model/todo.js) i change defaults to:

defaults: {string1: '', string2: '',somefloat: 0},

and in my collection (collections/todos.js) i comment out localstorage and add in a url.

This makes the fetch go to my server, and i can see that it returns the json collection.

But for some reason the model is undefined in backbone.js line 817

    // Prepare a model or hash of attributes to be added to this collection.
    _prepareModel: function (model, options) {
        options || (options = {});
        if (!(model instanceof Model)) {
            console.log(Model);
            var attrs = model;
            console.log(attrs.Kana);
            options.collection = this;

            //ERROR IN THIS LINE: Uncaught TypeError: undefined is not a function 
            model = new this.model(attrs, options);

            if (!model._validate(model.attributes, options)) model = false;
        } else if (!model.collection) {
            model.collection = this;
        }
        return model;
    },

Why is the model undefined when I'm not using localstorage?


Solution

  • You also need to set the property urlRoot in you Model:

    var TodoModel = Backbone.Model.extend({
    
        urlRoot: "/Practice/GetCollection",