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

时间:2015-01-18 08:35:16

标签: javascript json backbone.js

出于某种原因,我在我的JavaScript中遇到了一个关于假设的Backbone模型对象的TypeError,我试图将其称为“model.destroy()”:

这是我的Backbone代码:

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();
            }
        });
    }
});

所以我从node.js服务器获取数据,服务器返回JSON。 JSON有cid和所有爵士乐,因此这些对象曾经是Backbone模型。

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

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

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

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

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