Backbone - model.destroy() 函数未为模型定义

Backbone - model.destroy() function not defined for model

本文关键字:模型 定义 函数 model destroy Backbone      更新时间:2023-09-26

出于某种原因,我在JavaScript中收到一个TypeError,关于一个假定的Backbone模型对象,我试图称之为"model.destroy()":

这是我的主干代码:

var Team = Backbone.Model.extend({
    idAttribute: "_id",
    urlRoot: '/api/teams'
});
var TeamCollection = Backbone.Collection.extend({
    model: Team
});
var teamCollection = new TeamCollection([]);
teamCollection.url = '/api/teams';
teamCollection.fetch(
    {
        success: function () {
            console.log('teamCollection length:', teamCollection.length);
        }
    }
);
var UserHomeMainTableView = Backbone.View.extend({
    tagName: "div",
    collection: teamCollection,
    events: {},
    initialize: function () {
        this.collection.on("reset", this.render, this);
    },
    render: function () {
        var teams = {
            teams:teamCollection.toJSON()
        };
        var template = Handlebars.compile( $("#user-home-main-table-template").html());
        this.$el.html(template(teams));
        return this;
    },
    addTeam: function (teamData) {
        console.log('adding team:', team_id);
    },
    deleteTeam: function (team_id) {
        console.log('deleting team:', team_id);
        var team = teamCollection.where({_id: team_id}); //team IS defined here but I can't confirm the type even when logging "typeof"
        console.log('team to delete', typeof team[0]);
        console.log('another team to delete?',typeof team[1]);
        team.destroy({      //THIS FUNCTION CALL IS THROWING A TYPEERROR
            contentType : 'application/json',
            success: function(model, response, options) {
                this.collection.reset();
            },
            error: function(model, response, options) {
                this.collection.reset();
            }
        });
    }
});

所以我正在从节点.js服务器获取数据,并且服务器正在返回 JSON。JSON有cid和所有爵士乐,所以这些对象曾经是骨干模型。

我只是不知道为什么团队类型不会是骨干模型。

有什么想法吗?

.where返回一个数组。您需要改用.findWhere

或者对结果数组中的每个模型调用 destroy。

.where({...}).forEach(function(model){
    model.destroy();
});