Backbone.js集合不添加对象

时间:2012-03-12 21:59:31

标签: javascript backbone.js underscore.js

我正在尝试从服务器获取一个集合数据,并使用Backbone.js将其加载到我的集合对象中。我想在开始时获取这些数据,并使用这些数据加载我的html页面。但是,我从服务器下载的数据不会正确填充到集合中。收集长度为零,有谁知道我做错了什么?

(function ($) {
    window.Menu = Backbone.Model.extend({});

    window.MenuCollection = Backbone.Collection.extend({
        model: window.Menu,
        initialize: function() {
            _.bindAll(this, 'parse');
        },
        url: function(){
            return 'http://localhost:8080/testing/123';
        },
        parse : function(resp) {
            console.log(resp);
            // this prints:
            // "[{"name":"helloworld1"},{"name":"helloworld2"}]"

            this.add(resp);
            this.add(new Menu({name:"black perl"}));
            console.log(this);
            // the length of the object in the console log is 0
        }
    });

    window.MenuView = Backbone.View.extend({
        tagName: 'li',
        initialize: function() {
            _.bindAll(this, 'render');
        },
        render: function() {
            $(this.el).html('<span>'+this.model.get('name')+'</span>');
            return this;
        }
    });

    window.MenuListView = Backbone.View.extend({
        tagName: 'ul',
        initialize: function() {
            _.bindAll(this, 'render');
        },
        render: function() {
            this.model.each(function(menu) {
                $(this.el).append(new MenuView({model:menu}).render().el);
            });

            return this;
        }
    });

    var view;
    AppView = Backbone.View.extend({
        el: $("body"),
        initialize: function () {
            this.menus = new MenuCollection();
            this.menuListView = new MenuListView({model:this.menus});
            view = this.menuListView;
            this.menus.fetch({success: function(){console.log("success");
            console.log(view.render().el);}});
        },
        events: {

        }
    });

    var appview = new AppView;

})(jQuery);

3 个答案:

答案 0 :(得分:2)

你误解了parse的工作方式:

  

解析 collection.parse(response)

     只要服务器在fetch中返回集合的模型,Backbone就会调用

parse 。该函数传递原始response对象,并应返回要添加到集合中的模型属性数组。

因此,如果您从服务器获得[{"name":"helloworld1"},{"name":"helloworld2"}],则甚至不需要parse实施。

您在add看到的奇怪行为更有趣。如果我们查看fetch,我们会看到:

fetch: function(options) {
  //...
  options.success = function(resp, status, xhr) {
    collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
    if (success) success(collection, resp);
  };
  //...
}

您在没有设置fetch选项的情况下调用add,所以事情就是这样:

  1. collection.parse被召唤。
  2. 您的parse添加了一些内容并致电console.log
  3. 你的解析根本不会返回任何内容。
  4. collection.reset被调用以添加parse返回的内容。
  5. reset会清除收藏品,然后不添加任何内容,因为parse没有返回任何内容。
  6. 一些console.log实现在控制台中放置了一个实时引用,这就是你在控制台中获得一个空集合的原因:console.log(this)最终在之后显示this reset来电。{/ p>

答案 1 :(得分:1)

实际上,你遇到的另一个问题是你没有将“this”传递给视图渲染中for循环的上下文。因此,当您返回“el”元素时,您的html页面将为空白,而不包含服务器中的内容。

答案 2 :(得分:0)

请记住,解析方法可从backbone.js 0.9+获得 版本0.5.3不会调用解析。