Help us understand the problem. What is going on with this article?

Knockoutjs の with の代わりに template も使える子です

More than 5 years have passed since last update.

with と template と foreach

with/foreachはコンテキストが切り替わるからhtmlがカオスになりがち。

  • 今のコンテキスト($data)はなんだ?
  • $rootから再度ツリーを参照しまくったり。

適当なviewmodel
var vm = {
    book:{
        title:"ハイキュー!!",
        reviews:[
            {review:"16巻でた!"},
            {review:"熱い!"},
            {review:"かっこいい!!"}
        ]
    }
}
// ko.applyBindings(vm, document.getElementById("container"));

こんな感じに表示する(ダサい…)
image

withを使った場合

foreachのせいでwithの恩恵は1回しか得られない

withを使った場合
<div id="container">
    <div data-bind="with:book">
        <div data-bind="text:title"></div>
        <ul data-bind="foreach:{data:reviews, as:'review'}">
            <li data-bind="text:$root.book.title + review"/>
        </ul>
    </div>    
</div>

templateを使った場合

bookを変数を取り置ける

templateを使った場合
<div id="container">
    <div data-bind="template:{data:book, as:'book'}">
        <div data-bind="text:title"></div>
        <ul data-bind="foreach:{data:reviews, as:'review'}">
            <li data-bind="text:book.title + review"/>
        </ul>
    </div>
</div>

注意

templateはundefinedでも動く(!)

チェック
<!-- ko if:book -->
〜template〜
<!-- /ko -->

で囲うとか必要っぽい。

総括

適宜使い分けよう

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした