主干渲染集合返回一个对象

时间:2016-01-27 16:29:06

标签: json backbone.js collections

我有问题渲染我的视图...视图总是返回json对象中的最后一个:这是代码:

Router.js:

var list = new clientCollection();
var cards = new cardsView({model:list})
list.fetch({success: function (collection, response, options) {
            cards.render();
           }
});

Cards.js查看:

   ....
tagName: 'section',
className: 'list',
template: Handlebars.compile(cardsTemplate),
render: function () {

                var list = this.model.toJSON(),
                    self = this,
                    wrapperHtml = $("#board"),
                    fragment = document.createDocumentFragment();


                $(list).each(function (index, item) {

                    $(self.el).html(self.template({card: item}));

                    $.each(item.cards, function (i, c) {
                        var card = new cardView({model : c});

                        $(self.el).find('.list-cards').append(card.render().el);
                    });


                    fragment.appendChild(self.el);
                });

                wrapperHtml.append(fragment.cloneNode(true));
            },
    ...

这是我的json数据:

[
{"id":"9","name_client":"XXXXXXX","cards":[]},
{"id":"8","name_client":"XXXXXXX","cards":[{"id":"8","title":"xxxxx.it","description":"some desc","due_date":"2016-01-23","sort":"0"}]}
]

你能帮我渲染一下吗?

1 个答案:

答案 0 :(得分:1)

如果没有看到视图如何附加到DOM,很难确定,但您的问题似乎就是这一行......

backbone.js

这实质上是将集合中的每个元素渲染为此视图的完整内容,然后在每次迭代时替换它。请尝试将每个模板的内容附加到视图元素中。

此外,由于您使用collectionsthis.model.each(function(item) { // 'item' is now an instance of the Backbone.Model type // contained within the collection. Also, note the use // of 'this' within the iterator function, as well as // this.$el within a View is automatically the same as // $(self.el) this.$el.append(this.template({ card: item }); // ... and so on ... // By providing 'this' as the second argument to 'each(...)', // the context of the iterator function is set for you. }, this); 对此进行了标记,请注意迭代整个集合的更简单,更Backbone-y方式是:

unset TMOUT
export TMOUT=2880000

那里有很多包装,所以......