Backbone.js collection.on("add") not working

Backbone.js collection.on("add") not working

本文关键字:quot not working add js Backbone collection on      更新时间:2023-09-26

我试图构建一个简单的简历应用程序。我试图在向集合添加模型数组时启动add事件。事件应该简单地登录发生了某些事情的控制台中。不幸的是,似乎什么都没有发生。也没有记录错误。谁能给我点小费?

下面是事件处理程序:

$(document).ready(function(){
    //INITIALIZATION
    var resumeSectionCollection = new ResumeSectionCollection();
    var resumeSectionView = new ResumeSectionView();

    //setting up collection and adding data to it
    resumeSectionCollection.on("add", this.logme,this);
    resumeSectionCollection.add([careerObjectiveModel,workExperienceModel1,workExperienceModel2,workExperienceModel3,educationModel,softwareSkillsModel]);
});

下面是集合类:

var ResumeSectionCollection = Backbone.Collection.extend({
    model: ResumeSectionModel,  
    logme: function(model){
        console.log("in logme");    
    },
});

在您的$(document).ready回调函数:

$(document).ready(function(){
    //...
    resumeSectionCollection.on("add", this.logme,this);
    //...
});
在大多数情况下,

this将是window,所以你实际上在说:

resumeSectionCollection.on("add", window.logme, window);

但是在window中没有logme函数,您的logme函数在ResumeSectionCollection集合中。您可能想要更像这样的内容:

var ResumeSectionCollection = Backbone.Collection.extend({
    model: ResumeSectionModel,  
    initialize: function() {
        this.on('add', this.logme, this);
        // or
        // this.listenTo(this, 'add', this.logme)
    },
    logme: function(model) {
        console.log("in logme");    
    }
});

然后:

$(document).ready(function() {
    var resumeSectionCollection = new ResumeSectionCollection();
    var resumeSectionView = new ResumeSectionView();
    resumeSectionCollection.add([ careerObjectiveModel, workExperienceModel1, workExperienceModel2, workExperienceModel3, educationModel, softwareSkillsModel ]);
});