javascript - 主干 - 未为模型定义 model.destroy() 函数

标签 javascript json backbone.js

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

这是我的主干代码:

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 模型。

有什么想法吗?

最佳答案

.where 返回一个数组。您需要使用.findWhere相反。

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

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

关于javascript - 主干 - 未为模型定义 model.destroy() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28008398/

相关文章:

javascript - angularjs - ng-model 输入为字符串

javascript - 当用 Backbone.js 替换时,queryui 复选框按钮的内容会增加

javascript - BackboneJS。 View 加载后如何将纪元图添加到 View 中

javascript - 如何构建 Backbone 应用程序?

javascript - Highcharts 堆叠柱形图可以具有不规则的时间间隔吗?

javascript - 搜索字符串中的值,然后更新字符串

javascript - 显示/隐藏时爆炸/内爆文本(不展开但将页面重新组合回正常状态)

jquery - 使用JQuery和JSON格式的平面文件进行快速,动态的自动建议

json - 使用 JQ 将一个 JSON 文件值更新为另一个 JSON 文件值(在所有级别)

json - Gson 。 enum 和 int 的解决方法