题
我一直在使用 ractive.js,并试图了解它的功能。我有一个相当常见的例子,一个带有一些内部状态逻辑的视图,我想清楚地跟踪它。看完教程后,这似乎是 Ractive 真正擅长的事情,但我很难弄清楚这一点。
更新: 我根据收到的第一个答案中的反馈修改了下面的测试用例,以澄清我遇到的确切问题。您可以在此处查看完整的示例: http://jsfiddle.net/e7Mjm/1/
首先,我有一个反应模板:
<div id="toc-view"></div>
<script id="ractive-toc" type="text/ractive">
<ul>
{{#chapters}}
<li class="{{type}}">
<span class="ordinal">{{ordinalize(ordinal)}}</span>
<a data-id="{{element_id}}">{{title}}</a>
{{#(sections.length > 0)}}
<a class="{{open ? 'expand open' : 'expand'}}" on-click="toggleSections"></a>
{{#open}}
<ul class="{{open ? 'sections open' : 'sections'}}">
{{#sections}}{{>section}}{{/sections}}
</ul>
{{/open}}
{{/()}}
</li>
{{/chapters}}
</ul>
<!-- {{>section}} -->
<li class="{{type}}">
<span class="ordinal">{{ordinalize(ordinal)}}</span>
<a data-id="{{element_id}}">{{title}}</a>
</li>
<!-- {{/section}} -->
</script>
我有一些简单的 CSS 样式来格式化它:
ul { list-style: none; padding: 0; margin: 0}
ul.sections { padding-left: 20px; }
a.expand { color: red; }
a.expand:before { content: "+"; }
a.expand.open { color: blue; }
a.expand.open:before { content: "-"; }
下面的 Javascript 使其一切正常:
data = [
{
id: "smith-about",
title: "About this book",
type: "front-matter"
},
{
id: "smith-preface",
title: "Preface",
type: "front-matter"
},
{
id: "smith-ch01",
title: "Intro to Biology",
ordinal: "1",
type: "chapter",
sections: [
{
id: "smith-ch01-s01",
title: "What is biology?",
ordinal: "1.1",
type: "section"
},
{
id: "smith-ch01-s02",
title: "What is a biologist?",
ordinal: "1.2",
type: "section"
},
{
id: "smith-ch01-s03",
title: "So you want to be a biologist?",
ordinal: "1.3",
type: "section"
}
]
},
{
id: "smith-ch02",
title: "Applied Biology",
ordinal: "2",
type: "chapter",
sections: [
{
id: "smith-ch02-s01",
title: "Biology in the lab",
ordinal: "2.1",
type: "section"
},
{
id: "smith-ch02-s02",
title: "Biology in the field",
ordinal: "2.2",
type: "section"
},
{
id: "smith-ch02-s03",
title: "Biology in the classroom",
ordinal: "2.3",
type: "section"
}
]
}
]
ractive = new Ractive({
el: 'toc-view',
template: '#ractive-toc',
data: {
chapters: data,
ordinalize: function(ordinal) {
return ordinal ? ordinal + "." : "▸";
}
}
});
ractive.on('toggleSections', function(event) {
event.context.open = !event.context.open;
this.update();
});
如果您尝试 JS Fiddle,您将看到模板渲染正确,但交互行为不太正确: 如果您点击 a.expand
它确实打开了该部分,但它也更改了所有其他部分的类 a.expand
图标,而不仅仅是被单击的图标。
这是我一直遇到的真正问题,在活动事件绑定中,似乎没有一个很好的方法来定义仅影响用户正在与之交互的特定数据对象的交互,相反,交互似乎影响所有数据。
关于如何正确确定范围的任何见解?
解决方案
这是一个例子 http://jsfiddle.net/e7Mjm/
我改为
{{#open}}{{#sections}}{{>section}}{{/sections}}{{/open}}
现在,当您打开时,它将“按需”呈现
你可以使用 event.context
. 。做就是了
event.context.open = !event.context.open;
this.update();
不隶属于 StackOverflow