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

时间:2015-03-14 04:51:51

标签: ractivejs

我尝试使用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数据?

1 个答案:

答案 0 :(得分:1)

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

像这样:

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
});

我在这里创建了一个你的例子:http://jsfiddle.net/08huhfar/3/