2014-11-04 112 views
0

我想重用应用中的视图(以前打开的屏幕),但区域内容消失。如何防止Marionette做到这一点?区域内第二次显示父视图时,Marionette不显示子视图

var app = new Backbone.Marionette.Application(); 
    window.app = app; 

    app.addRegions({ 
    root: 'body' 
    }); 

    var View1 = Marionette.LayoutView.extend({ 
    template: _.template('<div>View1<div class="sub"></div></div>'), 
     regions: { 
     sub: '.sub' 
     } 
    }); 

    var View2 = Marionette.ItemView.extend({ 
    template: _.template('<div>View2</div>') 
    }); 

    var SubView = Marionette.ItemView.extend({ 
    template: _.template('<div>SubView</div>') 
    }); 

    var view1 = new View1(); 
    var view2 = new View2(); 
    var subView = new SubView(); 

    app.root.show(view1, { preventDestroy: true }); 
    view1.sub.show(subView, { preventDestroy: true }); 

    setTimeout(function() { 
    app.root.show(view2, { preventDestroy: true }); 
    setTimeout(function() { 
     app.root.show(view1, { preventDestroy: true }); 
    }, 500); 
    }, 500); 

或小提琴http://jsfiddle.net/ndr7262y/

回答

1

所以preventDestroy不停止子视图被破坏只是实际的区域本身。通过设计制造木偶鼓励破坏观点并重新初始化它们,以便清理工作得到妥善处理。这一轮,虽然一个办法是听时,正在显示视图,然后表示子

app.listenTo(view1, "show", function() { 
      view1.sub.show(subView) 
}); 

唯一的问题是,副视点仍然被破坏,所以你可以覆盖破坏子视图的方法不破坏认为,这变得有点棘手跟踪过,虽然和现在一样,你必须手动确保绑定正确应用/删除

var SubView = Marionette.ItemView.extend({ 
     template: _.template('<div>SubView</div>'), 
     destroy: function() { 

      if (this.isDestroyed) { 
       return; 
      } 

      var args = [].slice.call(arguments); 

      this.triggerMethod.apply(this, ['before:destroy'].concat(args)); 

      // mark as destroyed before doing the actual destroy, to 
      // prevent infinite loops within "destroy" event handlers 
      // that are trying to destroy other views 
      this.isDestroyed = false; 
      this.triggerMethod.apply(this, ['destroy'].concat(args)); 

      // unbind UI elements????? well its not beng destoryed so probably don;t wantto do this 
      //unless you manually handle rebind the events 
      //this.unbindUIElements(); 
      return this; 
     } 
    }); 

落脚点http://jsfiddle.net/ndr7262y/2/

,但更好的办法在这里会重新进入当视图1显示时,将子视图iatalize

app.listenTo(view1, "show", function() { 
      var subView = new SubView(); 
      view1.sub.show(subView) 
}); 

现在您不必担心清理或覆盖销毁方法。 http://jsfiddle.net/ndr7262y/4/