开发者

Using KnockoutJS template within jQuery template

I have a jQuery template, and I would like to use a KnockOutJS template within this.

I cannot make this work as this example illustrates: http://jsfiddle.net开发者_如何学C/maate/bwmcR/1/.

However, it DOES work when the KnockOutJS template itself is placed outside the scope of the jQuery template as in this example: http://jsfiddle.net/maate/bwmcR/2/.

It seems that the problem is related to the scope of the template data variables (for instance, I can access the ${test} variable within the subTemplate).

Does anyone know how to make this work?

Br. Morten


The first example you have is just not valid. Although you want to create a sub-template it has to be in a separate script tag. You just can't embed templates within each other, you have to create them one after the other. WRONG:

<script id="superTemplate" type="text/html">
...
<script id="subTemplate" type="text/html">
...
</script>
</script>

RIGHT:

<script id="superTemplate" type="text/html">
...
</script>
<script id="subTemplate" type="text/html">
...
</script>

When you applied the subtemplate on the ul, you defined what data it should be using with the foreach, so you won't be able to read the test as it is not a property on an item. If you want you can pass it as a templateOption so it will be available on the subtemplate too.

<ul data-bind="template: { name: 'subTemplate', foreach: items, templateOptions: { testValue: 'Value' } }"></ul>

This way it will be available on the subtemplate.

<span data-bind="text: $item.testValue"></span>

Also, I wouldn't use the default jQuery template tags, it is much nicer with data-binding.

<div id="body" data-bind="template:{name: 'superTemplate'}"></div>

It will do the same, more or less, in the end. You can take a look here : http://jsfiddle.net/bwmcR/18/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜