Backbone Marionette Region显示无渲染

时间:2013-10-21 14:05:51

标签: javascript backbone.js marionette

是否可以将已经渲染的视图放入骨干牵线木偶区域而不再渲染它?

例如:

region.show(myView); // This will call render on myView

我不希望该地区再次呈现我的观点。

如果我这样做:

region.attachView(myView); // This won't render myView, but it also won't show it

2 个答案:

答案 0 :(得分:2)

首先覆盖marionette ItemView构造函数并像这样渲染(如果你想在CollectionView中使用它,而CompositeView也会覆盖它们的这些方法):

var fnCons = Marionette.ItemView.prototype.constructor,
    fnRender = Marionette.ItemView.prototype.render;
Marionette.ItemView.prototype.constructor = function(){
  this.firstRender = true;
  fnCons.apply(this,arguments);       
}

Marionette.ItemView.prototype.render = function(){
  this.firstRender = false;
  fnRender.apply(this,arguments);
}

然后只需覆盖默认区域#show,如果view为view.firstRender为true,则表示尚未呈现,必须呈现它,否则无需任何操作。

Marionette.Region.prototype.show = function(view){    
  this.ensureEl();

  var isViewClosed = view.isClosed || _.isUndefined(view.$el);

  var isDifferentView = view !== this.currentView;

  if (isDifferentView) {
    this.close();
  }
  // These lines changed from default marionette action
  if(view.firstRender){
    view.render();
  }else{
    // Don anything else!
  }
  // End of overrided code


  if (isDifferentView || isViewClosed) {
    this.open(view);
  }

  this.currentView = view;

  Marionette.triggerMethod.call(this, "show", view);
  Marionette.triggerMethod.call(view, "show");
}

修改

上面的解决方案工作正常,另一种方式是(这将假设视图已呈现):

Marionette.Region.prototype.showWithoutRender = function(view){
  this.ensureEl();

  var isViewClosed = view.isClosed || _.isUndefined(view.$el);
  var isDifferentView = view !== this.currentView;

  if (view !== this.currentView) {
    this.close();
  }

  if(isViewClosed || isDifferentView){
    this.open(view);
  }
  this.currentView = view;

  Marionette.triggerMethod.call(this, "show", view);
  Marionette.triggerMethod.call(view, "show");
}

答案 1 :(得分:1)

// assume your view is already rendered
region.ensureEl();
region.open(myView);

这不建议使用,如果可以,请使用region.show(myView)。因为它会关闭前一个视图以清理所有事件监听器等等......