如何将事件绑定到尚未加载的模型?

时间:2012-01-18 08:52:09

标签: javascript backbone.js

所以我有一个非常简单的骨干应用程序,包含模型,集合和几个视图。我通过在页面加载时执行collection.fetch()来从服务器获取实际数据。

我的问题是我的一个视图是一个“细节”视图,我想将它绑定到一个特定的模型 - 但是当页面加载时我还没有模型。我的代码看起来很像这样:

window.App = {
    Models: {},
    Collections: {},
    Views: {},
    Routers: {}
}

App.Models.Person = Backbone.Model.extend({
    urlRoot: '/api/people'
});

App.Collections.People = Backbone.Collection.extend({
    model: App.Models.Person,
    url: '/api/people'
});

people = new App.Collections.People()

App.Views.List = Backbone.View.extend({
    initialize: function() {
        this.collection.bind('reset', this.render());
    },
    render: function() {
        $(this.el).html("We've got " + this.collection.length + " models." )
    }
});

listView = new App.Views.List({collection: people})

App.Views.Detail = Backbone.View.extend({
    initialize: function() {
        this.model.bind('change', this.render());
    },
    render: function() {
        $(this.el).html("Model goes here!")
    }
});

App.Routers.Main = Backbone.Router.extend({
    routes: {
        '/people': 'list',
        '/people/:id': 'detail'
    },
    list: function() {
        listView.render();
    },
    detail: function(id) {
        detailView = new App.Views.Detail({model: people.get(id)})
        detailView.render()
    }
})

main = new App.Routers.Main();
Backbone.history.start();
people.fetch();

但是,如果我从详细路线开始,people集合为空,那么people.get(id)不返回任何内容,因此我的新视图this.model未定义,并且赢了'让我绑定任何与之相关的事件。错误是:

Uncaught TypeError: Cannot call method 'bind' of undefined

如果我从列表路线激活开始,那么当我点击一个项目以显示详细视图people时,就会填充,所以一切正常。

在页面加载后获取数据时,为“详细信息”视图绑定模型相关事件的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以在此处获得部分答案:Backbone.js Collections not applying Models (using Code Igniter)

实际上,您需要等待people.fetch完成其ajax请求才能调用Backbone.history.start();并触发实际路由。

您的代码应如下所示:

// [...]
main = new App.Routers.Main();
peoples.fetch({
    success: function (collection, response) {
        // The collection is filled, trigger the route
        Backbone.history.start();
    }
});

您可以在页面上添加加载程序,并在加载集合时将其隐藏。