Why are div templates displayed as ": hidden" in afterRender?

Why are divs templates displayed as ": hidden" in afterRender?

Here is the code:

<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script src="js/jquery.tmpl.js"></script> <script src="js/knockout-1.2.1.debug.js"></script> <script> $(document).ready(function() { m = function (name) { this.name = name; } viewModel = { a : ko.observableArray(), sparkie : function (elements) { div = elements[0]; console.log($(div).is(':hidden')); }, } ko.applyBindings(viewModel); viewModel.a.push(new m('oh-no')); }); </script> </head> <body> <script type="text/html" id="tpl"> <div> ${ $data.name } </div> </script> <div data-bind='template: { name: "tpl", foreach: a, afterRender: sparkie }'></div> </body> </html> 
0
source share
2 answers

When afterRender is called to bind a template in foreach mode, the elements are not yet added to the DOM. Some additional processing is performed to ensure that the nodes are effectively added / removed.

However, instead, you can use the afterAdd when using the foreach parameter to execute the code after the elements are in the DOM.

+2
source

afterRender for

custom post processing logic in the DOM elements created by your templates

BUT, unfortunately, it is called after your template is ready (applied to the DOM), but it is not yet inserted into the html.

If you use foreach, the knockout will call an afterRender callback for each element added to the observable Array

but if it will also be called once, if you pass data to the template.

KO allows you to give afterAdd and / or beforeRemove callbacks to manipulate the added / removed DOM elements in a custom way

therefore, they will be called for each added / deleted item in the observed array. When they are called, your DOM is ready, so you will no longer hide, but these callbacks are only called when the main observable array changes.

 <div data-bind="template: { name: 'tpl', foreach: a, afterAdd: sparkie }"></div> 
+2
source

Source: https://habr.com/ru/post/1389846/


All Articles