简体   繁体   English

骨干-多个事件后呈现视图

[英]Backbone - Render view after multiple events

I have a Backbone View which I want to render only after two different events have happened. 我有一个骨干View ,仅在发生两个不同事件后才要渲染。 The two events are two different Collections being populated from the server (this is to populate two dropdown select lists). 这两个事件是从服务器填充的两个不同的Collections (这是填充两个下拉选择列表)。

My two Collections are cFilterFields and cFilterOperators and both have a custom .populate() method which calls .fetch() and fires populated events. 我的两个CollectionscFilterFieldscFilterOperators ,它们都有一个自定义的.populate()方法,该方法调用.fetch()并触发populated事件。

This is what I have: 这就是我所拥有的:

var MyView = Backbone.View.extend({
    tagName: 'div',
    initialize: function(){
        _.bindAll(this,'render');

        this.fields = new cFilterFields();
        this.operators = new cFilterOperators();

        this.fields.populate();
        this.operators.populate();

        this.listenTo(this.fields,'populated',function(){
            // ...
        });
        this.listenTo(this.operators,'populated',function(){
            // ...
        });

    },
    events: {},
    render: function(){
        // ...
        return this;
    }
});

What is the best way to render this View when both Collection events have fired...? 两个 Collection事件都已触发时,呈现此View的最佳方法是什么?

Have the collections' populate methods return promises and then use jQuery.when 让集合的populate方法返回Promise ,然后使用jQuery.when

Your initialize should then look something like this 您的初始化应该看起来像这样

$.when(fields.populate(), operators.populate())
  .done(_.bind(function() {
      this.render();
  }, this));

This solution assumes JQuery and underscore because both are dependencies of Backbone. 该解决方案假定使用JQuery和下划线,因为它们都是Backbone的依赖项。

Just done it, simple really, you just do: 刚刚完成,实际上很简单,您只需执行以下操作:

this.listenTo(this.fields && this.operators,'populated',function(){
    this.render();
});

UPDATE UPDATE

Don't use this, see comments below, I'll be accepting the correct answer. 不要使用它,请参阅下面的评论,我将接受正确的答案。

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

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