【问题标题】:RactiveJS: Render element on two nodesRactiveJS:在两个节点上渲染元素
【发布时间】:2015-09-29 05:05:25
【问题描述】:

是否可以在两个节点上渲染 Ractive 实例,以及如何做到这一点?例如,表格顶部和底部的分页。

index.html 会很傻:

...
<div id="mainBigTable">
   <div class="pagination"></div>

   <div id="dataTable"></div>  

   <div class="pagination"></div>
</div>
...

RactiveJS:

var paginationClass = Ractive.extend({
    template: template("paginationClassTemplate");
    init: function() {
        //Some initialization
    }
});

app.js 初始化:

paginationInstance = new paginationClass();
return paginationInstance.render("#mainBigTable .pagination");

所以我想在两个&lt;div class="pagination"&gt;&lt;/div&gt; 上使用一个paginationInstance

是否有可能以及如何实现?

谢谢!

【问题讨论】:

  • 这能给你一些建议吗? github.com/iamjoel/ractive-paging
  • 是的,这是我想要创造的东西。唯一不同的是我需要在其他组件中使用分页。

标签: ractivejs


【解决方案1】:

您不能在 2 个地方使用一个实例。即使是普通的 DOM 元素也无法做到这一点(如果您尝试将页面上的现有 DOM 元素附加到另一个 DOM 元素中,则会将其从原来的位置移除并呈现到目标)。

您始终可以为第二个分页组件创建单独的实例。为了使两个分页组件同步,您需要将数据提取到其他地方。您可以使用模型或可监听对象或父组件来存储分页数据,以便两个组件都可以监听数据变化。


这是一个包含两个分页实例的父组件示例:

<script type="template/ractive" id="template-parent">
  <div id="mainBigTable">
   <pagination currentPage="{{currentPage}}" pages="{{pages}}" />
   <div id="dataTable"></div>  
   <pagination currentPage="{{currentPage}}" pages="{{pages}}" />
  </div>
</script>

<script>
// So here we define a "parent" component that houses your pagination as
// it's components. In the template above, you see a custom element named
// after the component. It receives currentPage and pages from BigTable
var BigTable = Ractive.extend({
  template: '#template-parent',
  data: {
    // Defaults
    currentPage: 0,
    pages: 0,
  },
  components: {
    pagination: paginationClass
  }
});

// Now you treat bigTable as an instance too!
var bigTable = new BigTable({
  el: 'somewhere-in-your-page',
});

// Now all you need to do is change bigTable's data and it will
// trickle down to both pagination components
bigTable.set('currentPage', 3);
</script>

【讨论】:

  • 所以我需要创建两个paginationInstance 实例并将两个参数(而不是一个)传递给其他组件?如果我想在其他地方添加分页,我需要重构所有代码。没有别的办法吗?
  • @Orbitum 是的,是的。创建两个实例,向它们传递相同的数据。您可以将两者都包含在一个保存数据的活性组件中,这样两者就可以共享数据。另一种方法是使用可监听对象,即某种事件发射器,两个实例都可以监听数据变化。让我稍微更新一下答案。
猜你喜欢
  • 1970-01-01
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 2014-11-03
  • 2021-07-03
相关资源
最近更新 更多