Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  98] [ 5]  / answers: 1 / hits: 15443  / 13 Years ago, thu, february 16, 2012, 12:00:00

I've been searching for a while, and I'm pretty confident this is a new question, and not a repeat like the title suggests. :)



Basically, I'm trying to find out if there is a subscribe-able event that KnockoutJS creates after a template render when using something like jQuery templates.



I'd use the built-in afterRender but I found out that it doesn't fire if the observable array is cleared. I built this demo to illustrate that problem: http://jsfiddle.net/farina/YWfV8/1/.



Also, I'm aware that I could write a custom handler...but that seems really unnecessary for what I need.



I just want one event that fires after the template finishes rendering.


More From » jquery

 Answers
105

My colleague actually solved this last night using something we were playing with before I went home.



So the whole problem with the events “afterRender”, “afterAdd”, and “beforeRemove” is that they act differently in conjunction with a foreach binding. KnockoutJS is nice enough to tell you this on their page, but for whatever reason it didn't actually sink in for me until I saw it in practice.



What really works is to scrap the whole foreach binding and use Knockout's native data bind like this:



data-bind=template: { name: 'item-template', data: items, afterRender: caller }


Then afterRender works exactly as the name suggests.



I was under the impression that you couldn't iterate the collection and render new UI without foreach, but these examples illustrate that it does work.





I made an example for both ViewModel styles because I sometimes need one or the other.



Thanks for the help Dan!!


[#87434] Tuesday, February 14, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;