1

所以基本上我一直在玩弄这种 pubsub 模式,当父“控制器”视图调用时,子视图会重新渲染(对不起,如果这令人困惑)。如果子视图基于集合或模型的获取(下面未显示),有时它们不会以正确的顺序呈现我也需要它们,即如果 SubView1 是 Subview2 的小导航,我不想要它在 SubView2 下方。

我认为这样一个常见问题必须有一个模式。让我知道这是否没有意义,我会澄清一下。但我正在处理的基本情况如下。

标记:

 <div id="main-container">
   <div class="inner-container"></div>
 </div>

js:

 var ToggleNavView = Backbone.View.extend({
    //let's say this template has two links
    template: Handbars.compile(linkstmpl),

    el: $('#main-container'),
    events: {
      "click a": "toggleViews"
    }
    initialize: function(){
      _.bindAll(this, 'render', 'toggleViews');

      // whoa, nice looking event aggregator http://bit.ly/p3nTe6
      this.vent = _.extend({}, Backbone.Events);

      this.render();
    },
    render: function(){
       $(this.el).append(this.tmpl);

       // suppose subviews below are declared as modules above with, say, requirejs
       var sub1 = new SubView1({ vent: this.vent }),
           sub2 = new SubView2({ vent: this.vent });


    },

    toggleViews: function(e){
      e.preventDefault();

      // get name of section or view you're toggling to
      var section = $(e.currentTarget).data('section');

      // publish events to subscribers
      this.vent.trigger('toggleInboxViews', this, section);


    },

   });

   var SubView1 = Backbone.View.Extend({
      template: Handlebars.compile(tmpl1),
      initialize: function(ops){
        _.bindAll(this, 'render', 'removeOrRerender');

        this.vent = ops.vent || null;
        this.render()
      },
      render: function(){
        $(this.el).append(this.template()).appendTo($(".inner-container"))
      },

      removeOrRerender: function(obj, section){
        if( section == 'my-section'){
          this.render();
        } else if( section == 'other-section' ) {
          $(this.el).fadeOut();
        }
      },

    })

    // another subview with same functionality etc... 

    // init view
    new ToggleNavView();
4

1 回答 1

1

如果您需要子视图显示在特定位置,则父视图应定义该结构,并且应告知子视图在何处呈现自身。然后,由于整体结构不会改变,因此绘制的顺序无关紧要。

例如,如果您希望一个子视图显示在顶部,另一个显示在其下方,则主视图应如下所示:

<div id="main-view">
    <div id="sub1"></div>
    <div id="sub2"></div>
</div>

然后主视图将使用以下内容呈现子视图:

 var sub1 = new SubView1({ el: this.$el.find('#sub1'), vent: this.vent }),
 var sub2 = new SubView2({ el: this.$el.find('#sub2'), vent: this.vent });

通过el为子视图指定 ,它们在页面上的位置不再是它们的问题,并且如果它们以不同的顺序呈现,它们也不会移动位置。这种结构的一个愉快的副作用是子视图只关心它们自己并且很好地独立。父视图只需要通过正确构造其模板将各个部分放在正确的位置,并且一切正常。

这是一个可以阐明结构的简单演示:http: //jsfiddle.net/ambiguous/9u3S5/

于 2012-05-02T23:26:10.803 回答