私は 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 イベントバインディングでは、ユーザーが操作している特定のデータオブジェクトのみに影響を与える操作を定義するのにあまり良い方法はないようです。すべてのデータに影響を与えます。
これを正しくスコープする方法についての洞察はありますか?