Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a variable in a template binding?

I know this isn't a good method to use long term, but for troubleshooting, is there any way I can pass a simple string while binding a template and then access it as a variable within the template? For instance, if this was my binding:

<!-- ko template: { name: tmplOne }, myvar: 'apple' -->

and this was tmplOne:

<div>
    <span>Fruit: </span>
    <span data-bind="text: myvar"></span>
</div>

It would result in the folowing:

fruit: apple

Even if I have to declare an observable in the viewmodel called "fruit", can I manually set it at template binding?

like image 466
THE JOATMON Avatar asked Dec 06 '13 18:12

THE JOATMON


3 Answers

Use

<!-- ko template: { name: tmplOne, templateOptions: {myvar: 'apple'} } -->

More here: http://www.knockmeout.net/2011/03/quick-tip-reusing-template-by-passing.html

like image 85
Ainsof Avatar answered Oct 26 '22 16:10

Ainsof


You can supply a data parameter to the template binding and define an object literal if you want just like you are doing:

<!-- ko template: { name: tmplOne }, myvar: 'apple' -->

instead do this:

<!-- ko template: { name: tmplOne, data: { myvar: 'apple' } } -->

http://knockoutjs.com/documentation/template-binding.html

like image 20
Organiccat Avatar answered Oct 26 '22 14:10

Organiccat


For people reading on later versions of knockout, this would appear to be a good usecase for components vs templates.

like image 1
Ryan Leach Avatar answered Oct 26 '22 15:10

Ryan Leach