Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout data-bind on dynamically generated elements

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?

like image 435
King Julien Avatar asked Jun 16 '12 20:06

King Julien


People also ask

What is data bind Knockout?

Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

What is KnockoutJS in asp net?

Knockout. Js (simply KO) is a powerful JavaScript library which allows developers to bind DOM elements with any data model like array, Json etc.


1 Answers

If you add this element on the fly after you have bound your viewmodel it will not be in the viewmodel and won't update. You can do one of two things.

  1. Add the element to the DOM and re-bind it by calling ko.applyBindings(); again
  2. OR add the list to the DOM from the beginning and leave the options collection in your viewmodel empty. Knockout won't render it until you add elements to options on the fly later.
like image 113
PlTaylor Avatar answered Sep 23 '22 06:09

PlTaylor