我一直在玩ractive.js,并试图了解它的功能。我有一个相当常见的例子,一个带有一些内部状态逻辑的视图,我想干净地跟踪它。经过教程后,这似乎是Ractive真正擅长的东西,但我很难搞清楚这一点。
更新:我根据我得到的第一个答案中的反馈修改了我的测试用例,以澄清我遇到的确切问题。您可以在此处查看完整示例:http://jsfiddle.net/e7Mjm/1/
首先,我有一个ractive模板:
<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
图标的类,而不仅仅是点击的图标。
这是我一直存在的真正问题,在ractive事件绑定中,我似乎没有一种非常好的方式来定义仅影响用户正在与之交互的特定数据对象的交互,而是这种互动似乎会影响所有数据。
有关如何正确确定范围的任何见解?
答案 0 :(得分:1)
我改为
{{#open}}{{#sections}}{{>section}}{{/sections}}{{/open}}
现在,当您打开
时,它将呈现“按需”您可以使用event.context
。只是做
event.context.open = !event.context.open;
this.update();