knockout data-bind on dynamically generated elements

8,253 views
Skip to first unread message

levani

unread,
Jun 16, 2012, 4:50:36 PM6/16/12
to knock...@googlegroups.com
How is it possible to make knockout data-bind work on dynamically generated elements? For example, I insert a simple html select menu inside a div and want to populate options using the knockout options binding. This is what my code looks like:

$('#menu').html('<select name="list" data-bind="options: listItems"></select>');

but this method doesn't work. Any ideas?

Michael "Kato" Wulf

unread,
Jun 16, 2012, 5:40:06 PM6/16/12
to knock...@googlegroups.com
You just need to use applyBindings() after you render the element.

--
Michael Wulf


Boris Rosenow

unread,
Jun 18, 2012, 9:29:21 AM6/18/12
to knock...@googlegroups.com
Depends on what exactly you are trying to achieve. If you just want parts of your view being rendered at a later point in time with a pre-defined data structure, you could use the "with" control flow binding with an observable object: http://jsfiddle.net/bombo/ZbxbQ/2/

If you have more dynamic structures and want to render a templates in accordance to those structures, you could use the "template" binding. The following examples receives the used template name by a supplied view model function, and only renders, if the observable used as data parameter has any value: http://jsfiddle.net/bombo/JxSrQ/34/

Hope one of these can help you.

Regards,
Boris

Boris Rosenow

unread,
Jun 20, 2012, 10:17:40 AM6/20/12
to knock...@googlegroups.com
Please ignore the empty script tag in my first fiddle. Just forgot to remove that. :)

jna...@gmail.com

unread,
Sep 27, 2012, 1:25:30 PM9/27/12
to knock...@googlegroups.com
What if you want to apply the bindings to the generated elements, but the elements bind to a specific object in the model's tree?  For instance, you have an ajax-loaded modal display to edit an object in an observable array.  How do you call applyBindings and write a data-bind attribute so that the modal form elements bind to the specific object in the array?

Thanks! 

a.f.h...@gmail.com

unread,
Mar 7, 2013, 5:33:19 AM3/7/13
to knock...@googlegroups.com, jna...@gmail.com
Did you ever figure it out?

hac...@gmail.com

unread,
Apr 16, 2013, 2:13:00 PM4/16/13
to knock...@googlegroups.com
I've posted a simple example for dinamically adding an observable into the view model tree in StackOverflow. Hope it helps.

Hasen el Judy

unread,
Apr 16, 2013, 10:46:47 PM4/16/13
to knock...@googlegroups.com, jna...@gmail.com
Why would you insert or remove elements using jQuery? Always use knockout itself: if, with, and template.

soha...@gmail.com

unread,
May 20, 2013, 8:52:31 AM5/20/13
to knock...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages