1

我正在尝试使用 Ractive 组件实现单页应用程序,并且我需要一些页面范围的选项。我确实喜欢这样:

...
data: {
    options: {
        someOption: true
    },
...

当我使用它时一切都很好{{#if options.someOption}},但后来我遇到了一个问题 -rective.get('options.someOption')返回未定义(都带有ractive.get('options'))。观察也不起作用。有什么方法可以让我的代码理解我吗?

UPD。意外解决了一部分魔法的问题 - 当我将 {{options.someOption}} 放在模板上时,get() 开始工作。

4

1 回答 1

2

实例(包括组件)内的 Ractive 编程数据访问目前只能“看到”以下数据:

  1. 定义为数据
  2. 明确指定为组件参数
  3. 在模板中用作参考

对于 #1,您可以将选项作为默认数据包含在内,它将对所有实例可用:

Ractive.default.data = {
    options: {...}
}

任何新的 Ractive 实例,包括组件,都会有一个optionsdata 属性。

对于#2,即使您有深度嵌套的组件,您也可以让需要数据的组件的父级将其作为参数包含在内:

// Component somewhere in the "app" hierarchy.
// By referencing {{options}} in its template, it will find that data
// make it explicit on the widget component, which can then use it
// programmatically

<widget options='{{options}}'/>

对于#3,您可以在组件模板中包含一个“虚拟”引用:

// by using it in the template, it is now available for programatic access
{{#with options}}{{/with}}

当然还有 #4,增强 Ractive 以允许在代码中与模板进行相同的查找

于 2014-09-18T13:00:24.293 回答