Alexander Mills
Alexander Mills

Reputation: 100486

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

For some reason, I am getting a TypeError in my JavaScript regarding a supposed Backbone model object for which I am trying to call "model.destroy()":

Here's my Backbone code:

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

So I am fetching the data from the node.js server, and the server is returning JSON. The JSON has cid's and all that jazz, so those objects were once Backbone models at some point.

I just don't know why the type of team would not be a Backbone model.

Any ideas?

Upvotes: 0

Views: 106

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

.where returns an array. You need to use .findWhere instead.

Or call destroy for every model in the resulting array.

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

Upvotes: 2

Related Questions