【问题标题】:re-render Backbone view with new models使用新模型重新渲染主干视图
【发布时间】:2014-12-08 16:32:10
【问题描述】:

基本上,我想从集合中随机呈现一个标题列表,然后在用户触发“loadMore”标题事件时使用不同的标题集重新呈现该列表。

我有一个 StoryList 视图,它为我的集合中的每个模型附加了一个新的 StoryListItem 视图。我还使用下划线方法 sample() 来随机化和限制模型的数量,从而限制渲染的 StoryListItem 视图的数量。最后,我有一个委托给这个视图的事件,称为“loadMore”。我希望 loadMore 事件使用与原始集合不同的样本重新渲染视图。

目前,loadMore 事件基本上重构了原始集合(采样模型包含属性“models”,其中包含我们最初采样的所有模型),然后重新渲染视图。结果是在原始视图元素之后附加了第二个视图元素。我只知道我的方法不对,我希望有人可以让我走上正确的道路。

sbk.StoryListView = Backbone.View.extend({
        tagName: 'ul',
        id: 'story-list',
        initialize: function () {
            this.collection.on('reset', this.render, this);
            console.log('initialize');
        },
        template: Handlebars.compile($('#story-list-template').html()),
        render: function () {
            var newCollection = _.sample(this.collection.models, 4);
            _.each(newCollection, function (storyItem) {
                $(this.el).append(new sbk.StoryListItemView({model: storyItem}).render().el);
            }, this);

            $(this.el).append(this.template());
            return this;
        },
        events: {
            'click #load-more' : 'loadMore'
        },
        loadMore: function(){
            this.collection = new Backbone.Collection(this.collection.models);
            this.render();
        }
    });

【问题讨论】:

    标签: backbone.js underscore.js


    【解决方案1】:

    不用追加,只需替换视图元素的html即可。

    this.$el.html(this.template())
    

    【讨论】:

    • 这也可以,只要我先插入 StoryListView 模板,然后附加/前置 StoryListItem 视图。否则 .html() 将清除 StoryListItem html。我选择这个答案是因为它比我的解决方案少一步。谢谢。
    【解决方案2】:

    使用 this stackoverflow question 中回答的 Jquery 的 empty() 方法。

    loadMore: function(){
            this.collection = new Backbone.Collection(this.collection.models);
            this.$el.empty();
            this.render();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2014-09-18
      • 2014-11-13
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      相关资源
      最近更新 更多