I have several knockoutjs foreach template bindings which create about 100 <div class='item' />
in different positions all over my page - all works perfectly except that my subsequent jQuery calls do not work unless I stop in the debugger and wait a second before the jquery bindings are applied:
ko.applyBindings(viewModel);
$(".item").draggable();
I was looking for a dataBound event which I could use to apply my bindings AFTER the viewModel has been bound, but I do not find anything.
To apply bindings for the whole HTML document, it can be done using the Knockout function applyBindings() with passing the view model as the first and the only parameter: ko. applyBindings(viewModel); To apply Knockout for a part of the HTML document, pass the DOM element as a second parameter: ko.
A ViewModel can be any type of JavaScript variable. In Example 1-3, let's start with a simple JavaScript structure that contains a single property called name .
Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.
To read the observable's current value, just call the observable with no parameters. In this example, myViewModel. personName() will return 'Bob' , and myViewModel. personAge() will return 123 .
As Tyrsius mentions you can use the afterRender handler, you can also use the afterAdd handler depending on if you want to add/remove items from your list. These are covered on both the foreach and template binding docs.
You could also write your own custom binding to do the same, similar to this example. I recommend this as the most maintainable and reusable option but it is sometimes overkill.
That said, if you want to use draggable there is a great custom binding already out there which you maybe able to adapt.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With