【问题标题】:Render view on click event在点击事件上渲染视图
【发布时间】:2015-10-16 18:58:31
【问题描述】:

有没有办法让 CompositeView 中包含的 ItemViews 仅在单击按钮时呈现? 我想更改集合以更新复合视图的 dom,但每个单独的 ItemView 在需要之前不应该呈现。

如果我的描述有点含糊,请原谅我,但我对骨干和木偶的了解非常有限。

【问题讨论】:

  • 如果你能把你已经完成的代码放进去会很棒,我们从你卡住的地方继续:)

标签: javascript backbone.js marionette


【解决方案1】:

众所周知,Marionette 渴望获取您的复合(或集合)视图的子视图并生成它们。这就是为什么包含在复合视图render 方法中的是_renderChildren 进程。一旦被调用,就真的没有办法选择性地渲染子视图了。

但是有一个后门可以绕过渲染整个集合。这是一个简单的 initializing 你的 Composite View 与一个空集合,像这样

//Define MyCollection` and MyCompositieView and then...
var myCollection = new MyCollection(); // Construct an empty collection

var myCompositeView = new MyCompositeView({ collection: myCollection });

一个“空”的 Composite View 会正常渲染它自己的模板,直接跳过_renderChildren

然后您可以连接一个事件来调用myCompositeView.collection.add(model)。您会注意到 Marionette 在您的收藏中侦听 add 事件,

_initialEvents: function() {
  if (this.collection) {
    this.listenTo(this.collection, 'add', this._onCollectionAdd);

    // Other _initialEvents methods...
  }
},

_onCollectionAdd负责渲染添加的模型:

_onCollectionAdd: function(child) {
  this.destroyEmptyView();
  var ChildView = this.getChildView(child);
  var index = this.collection.indexOf(child);
  this.addChild(child, ChildView, index);  // The rendering happens here
},

把它们放在一起

要完成这项工作,您必须在 CompositeView 内但在该视图的集合之外有一个模型数组。我通常只是连接$.getJSON(或任何其他 AJAX 方法)来获取数据并将其存储在 View 对象的属性中。假设你在初始化时这样做:

initialize: function() {
  var that = this,
      dataUrl = "some/url";
  $.getJSON(dataUrl, function(data) {
    that.myModels = data;
  });
},

而且,在您的复合视图中,您可能会有一个事件,比如点击复合视图的元素:

events: {
  'click button': 'addChild'
}

addChild: function (event) {
  // functionality to identify which child to add to the collection
  this.collection.add(this.myModels[j]); // Where 'j' is the index the model you want lives in.
});

addChild 被调用时,集合会添加正确的模型,Mariontte 会确保渲染一个填充了该模型的子视图。

如何做到这一点有多种变化,您不必在视图中连接事件。但我想我证明了如何让方法独立呈现。如果您提供更多信息,我可以为您提供更多想法。

【讨论】:

  • 我非常感谢您简洁明了的描述。像魅力一样工作!
  • 我的压力,很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多