简体   繁体   中英

Backbone View says model is undefined?

i'm trying to get my feet wet with Backbone, but I can't figure out what's wrong here:

var  ToDoApp = {
            model: Backbone.Model.extend({
                default:function(){
                    return {
                        task: '',
                        completed:false
                    }
                }
            }),
            collection: Backbone.Collection.extend({
                model: this.model
            }),
            view: Backbone.View.extend({
                model: new this.model(),
                tagName: 'li'
            })
        }
console.log(new ToDoApp.model());

I get an 'undefined is not a function' on the model for the view. What's going on?
Also, does the view even need to have a model there? Sorry if that's a really basic question, I still don't quite understand fully how backbone works.

This part:

collection: Backbone.Collection.extend({
    model: this.model
})

will be executed when you're building ToDoApp but this won't be ToDoApp at that time, this will probably be window and window won't have a model property. The result is that you're actually saying:

collection: Backbone.Collection.extend({
    model: undefined
})

Similar problems happen here:

view: Backbone.View.extend({
    model: new this.model(),
    tagName: 'li'
})

The easiest thing to do is build ToDoApp piece by piece:

var ToDoApp = { };
ToDoApp.model = Backbone.Model.extend({ ... });
ToDoApp.collection = Backbone.Collection.extend({
    model: ToDoApp.model
});
ToDoApp.view = Backbone.View.extend({
    tagName: 'li'
});

Then you'd create the model for you view instance when you create the view instance:

var model = new ToDoApp.model();
var view  = new ToDoApp.view({ model: model });

Also, using names like ToDoApp.Model , ToDoApp.Collection , and ToDoApp.View would be more common for your "classes".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM