主干.js未捕获的类型错误:对象 [对象数组] 没有方法“on”

Backbone.js Uncaught TypeError: Object [object Array] has no method 'on'

本文关键字:对象 数组 有方法 on js 错误 类型 主干      更新时间:2023-09-26

谁能帮我解决这个问题?我不知道出了什么问题。

从 json 文件获取数据:

this.categoryTrees = new CategoryTrees();
this.categoryTrees.getCategoryTreesFromJSON();
this.categories = new Categories();
this.categories.getCategoriesFromJSON();

为其创建视图:

//view for startscreen
this.startscreenView = new StartscreenView({collection: this.categoryTrees});
//view for subjectsList
this.subjectsListView = new SubjectsListView({collection: this.categories.where({ category_tree : "onderwerpen" }) });

第二个带有 where 子句的给了我一个错误:未捕获的类型错误:对象 [对象数组] 没有方法 'on'

当我不放置 where 子句时,它工作得很好。在控制台中,我可以毫无问题地执行 where 功能。

我在这里错过了什么吗?

where 方法将返回集合中与传递的属性匹配的所有模型的数组。 因此,它不会返回Backbone.Collection因此您会得到on未定义的错误。

您需要从where的结果创建一个新的Categories集合:

this.subjectsListView = new SubjectsListView({
    collection: new Categories(
        this.categories.where({ category_tree : "onderwerpen" })) 
});

找到了一个合适的解决方案。在启动主干应用程序之前,我在一个新函数 loadDataAndStartApp() 中检索 JSON 数据。此函数在 dom 准备就绪时加载,加载 JSON 后,它将启动主干应用。这样,您就可以确保拥有所有可用数据。结合nemesv所说的关于创建一个新的类别函数以及他回答的其他建议,我为这个问题制定了以下答案。

var AppRouter = Backbone.Router.extend({
routes: {
    "": "startscreen",
    "Onderwerpen": "subjectsList"
},
initialize: function  (options) {

    this.categories = new Categories( options.categories );

    this.subjectsListView2 = new SubjectsListView({
        collection: new Categories(
            this.categories.where({ parent : null, name : "Evenwicht" })
        )
    });
    //view for spacesList

},
startscreen: function () {
    $('#app').html(this.startscreenView.render().el);
},
subjectsList: function () {
    $('#app').append(this.subjectsListView2.render().el);
},
});
function loadDataAndStartApp(){
var categories     = []
// LOAD APP DATA
$.ajax({
    url      : './catalogue.json',
    dataType : 'json'
}).done(function(data){
    console.log('Catalogue retrieved');
    // GET CATEGORIES
    _.each(data.categories, function( categorieObj ){
        var categorieName       = _.keys(categorieObj)[0],
            categorieAttributes = categorieObj[categorieName];
        categories.push( categorieAttributes );
    });
    // START APP
    var app = new AppRouter({ 
        categories     : categories
    });
    Backbone.history.start();
});
}

$(function(){
// ON DOM READY
loadDataAndStartApp();
});