简体   繁体   English

backbone.js - 渲染视图

[英]backbone.js - rendering view

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). 出于某种原因,当我第一次访问加载此视图的页面时,会显示5个项目(应该会发生)。 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. 但是当我通过单击<span>10</span>点击“setperpage”事件时,即使更新了url然后调用fetch() ,列表也不会更新。 (I've watched the requests w/ firebug, so I know I'm getting back 10 items in json). (我已经看过萤火虫的请求了,所以我知道我要回到json的10件物品)。 Why don't they re render? 他们为什么不渲染? I still only see 5 items. 我仍然只看到5个项目。

The this.collection.fetch(); this.collection.fetch(); is asynchronous so the call to render will still be using the old data. 是异步的,因此对render的调用仍将使用旧数据。

You need to wait for the fetch() to complete before calling the render function. 在调用render函数之前,需要等待fetch()完成。

In your initialize function, bind to the render function to the "reset" event. 在初始化函数中,将render函数绑定到“reset”事件。

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

When you need new data, call 当您需要新数据时,请致电

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM