1

したがって、基本的には、親の「コントローラー」ビューによって呼び出されたときにサブビューが再レンダリングされる pubsub のこのパターンをいじっています (混乱している場合は申し訳ありません)。サブビューがコレクションまたはモデルのフェッチに基づいている場合 (以下には表示されていません)、正しい順序でレンダリングされないことがあります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

サブビューを特定の場所に表示する必要がある場合は、親ビューでその構造を定義し、サブビューにレンダリングする場所を指定する必要があります。全体の構造は変わらないので、描画する順序は問題になりません。

たとえば、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 に答える