2

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

从 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 子句的第二个给我一个错误: Uncaught TypeError: Object [object Array] has no method 'on'

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

我在这里想念什么吗?

4

2 回答 2

2

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

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

this.subjectsListView = new SubjectsListView({
    collection: new Categories(
        this.categories.where({ category_tree : "onderwerpen" })) 
});
于 2013-11-07T16:20:12.323 回答
1

找到了合适的解决方案。在启动主干应用程序之前,我在新函数 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();
});
于 2013-11-09T12:30:53.310 回答