Ractive.js: Ractive.extend() 全局数据

Ractive.js: Ractive.extend() global data

我尝试使用 Ractive.js 向菜单添加一个按钮,单击此按钮侧边栏应该会打开。

js:

var ractive_setup = Ractive.extend({
  data: {
    data: {
      sidebar: false,
    }
  },
  onrender: function ( options ) {
    this.on({
      sidebar: function () {
        this.toggle('sidebar');
        console.log ( this.get('sidebar') );
      }
    });
  }
});

var ractive_sidebar_open = new ractive_setup({
  template: '#sidebar-open',
  el: '[data-ractive=sidebar-open]'
});

var ractive_sidebar = new ractive_setup({
  template: '#sidebar',
  el: '[data-ractive=sidebar]'
});

html:

<nav data-ractive="sidebar-open"></nav>
<script id="sidebar-open" type="text/ractive">
  <button class="open" on-click="sidebar">open sidebar</button>
</script>

<aside data-ractive="sidebar"></aside>
<script id="sidebar" type="text/ractive">
  {{ #if sidebar }}
  <button on-click="sidebar">close sidebar</button>
  <div class="sidebar-content">sidebar content</div>
  {{ /if sidebar }}
</script>

button.open 单击时,数据仅更改 ractive_setup 的一个实例——第一个实例。

如何为两个 ractive_setup 实例全局修改 Ractive 数据?

您需要在外部声明您的数据对象,并将其传递到您的 ractive_setup 的两个实例中。启用 magic mode (docs) 选项后,当您的数据被修改时,两个实例都会重新呈现。

像这样:

var ractive_setup = Ractive.extend({
  magic: true, //Magic mode to ensure re-render when data is modified
  onrender: function ( options ) {
    this.on({
      sidebar: function () {
        this.toggle('sidebar');
        console.log ( this.get('sidebar') );
      }
    });
  }
});

//declaring your data-object outisde, so you can pass it into both instances
var dataObj = {
    sidebar: false
};

var ractive_sidebar_open = new ractive_setup({
  template: '#sidebar-open',
  el: '[data-ractive=sidebar-open]',
  data: dataObj //passing in data to the first instance
});

var ractive_sidebar = new ractive_setup({
  template: '#sidebar',
  el: '[data-ractive=sidebar]',
  data: dataObj //passing in data to the second instance
});

我在这里为您的示例创建了一个有效的 fiddle:http://jsfiddle.net/08huhfar/3/