javascript Backbone.js - 渲染视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5681246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:01:18  来源:igfitidea点击:

backbone.js - rendering view

javascriptjquerybackbone.jsunderscore.js

提问by Matthew

My ListClass looks like this:

我的 ListClass 看起来像这样:

var ListView = Backbone.View.extend({

    initialize: function() {
        this.render();
    },  

    events: {
        'click ul#perpage span': 'setperpage'
    },

    setperpage: function(event) {
        this.collection.perpageurl = '/perpage/' + $(event.target).text();
        this.collection.fetch();
        this.render();
    },

    render: function() {

    template = _.template('\
    <table>\
    <% _(collection).each(function(model){%>\
    <tr><td><%=model.id%></td><td><%=model.name%></td><td><%=model.email%></td></tr>\
    <%}); %>\
    </table>\
    <ul id="perpage">\
    <li><span>5</span></li>\
    <li><span>10</span></li>\
    </ul>\
    ');

        var context = {collection: this.collection.toJSON()};
        $(this.el).html(template(context));
        $('#app').html(this.el);
        return this;
    }
});

For some reason, when I first visit the page that loads this view, 5 items show up (which is supposed to happen). But when I hit the "setperpage" event by clicking the <span>10</span>, even though the url is updated and then fetch()is called, the list never updates. (I've watched the requests w/ firebug, so I know I'm getting back 10 items in json). Why don't they re render? I still only see 5 items.

出于某种原因,当我第一次访问加载此视图的页面时,会显示 5 个项目(这是应该发生的)。但是当我通过单击 来点击“setperpage”事件时<span>10</span>,即使 url 被更新然后fetch()被调用,列表也永远不会更新。(我看过带萤火虫的请求,所以我知道我在 json 中取回了 10 个项目)。他们为什么不重新渲染?我仍然只看到 5 个项目。

采纳答案by Paul Perigny

The this.collection.fetch();is asynchronous so the call to render will still be using the old data.

this.collection.fetch();是异步的,因此对渲染的调用仍将使用旧数据。

You need to wait for the fetch() to complete before calling the render function.

在调用渲染函数之前,您需要等待 fetch() 完成。

In your initialize function, bind to the render function to the "reset" event.

在您的初始化函数中,将渲染函数绑定到“重置”事件。

this.collection.on("reset", function() { this.render(); }, this);

When you need new data, call

当您需要新数据时,请致电

this.collection.fetch({reset: true});