1

您好我正在寻找将 JSON 加载到 Backbone 集合的适当解决方案。我看到很多关于这个问题的帖子,但我仍然不明白如何正确地做到这一点。例如,你能解释一下为什么这个项目不起作用吗? http://blog.joelberghoff.com/2012/07/22/backbone-js-tutorial-part-1/

编辑:
当我使用 Firebug 查看结果时,它显示了一个空对象,集合为空。为什么?
编辑:
嗯,仍然不起作用:/现在我在萤火虫和一页中看不到任何东西。:(

        $(function() {
            var Profile = Backbone.Model.extend();

            var ProfileList = Backbone.Collection.extend({
                model: Profile,
                url: 'profiles.json'
            });   

            var ProfileView = Backbone.View.extend({
                el: "#profiles",
                template: _.template($('#profileTemplate').html()),
                render: function(eventName) {
                    _.each(this.model.models, function(profile){
                        var profileTemplate = this.template(profile.toJSON());
                        $(this.el).append(profileTemplate);
                    }, this);

                    return this;
                }
            });

            var profiles = new ProfileList();    
            var profilesView = new ProfileView({model: profiles});
            var profiles = new ProfileList(); 
            profiles.fetch();
            profiles.bind('reset', function () {
                console.log(profiles);
                profilesView.render();
            });

        });
4

1 回答 1

3

您的 fetch 调用是异步的,因为我确信它是在教程中编写的。因此,当您执行 时console.log,您的集合仍然是空的。
在教程中更进一步..:

var profiles = new ProfileList(); 
profiles.fetch({reset: true});
profiles.bind('reset', function () { console.log(profiles); });

这应该有效。

于 2013-04-10T13:29:47.360 回答