Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Asynchronous Constructor Instantiation and DOM Insertion Within Loop

$
0
0
Hey All,

How can I best instantiate a constuctor function and insert the associated HTML code into the DOM in a loop? At this point I'm using a callback from a setTimeout zero. Meh.

In this simplified example, I instantiate 1000 Button objects from the Button() constructor function, and insert them into the #pageContent div. The return value of the Button constructor is set up to return a rendered HTML view from a template, as well as static and prototype and variables and methods defined as an extension of can.Construct:

  1. // Happily adds buttons to page one at a time, as they are instantiated
  2. var $pageContent = $('div#pageContent');
  3. for (var count = 0; count < 1000; count++) {
  4.       setTimeout( function() {
  5.             var myButton = new Button();
  6.             $pageContent.append(myButton);
  7.       }, 0 );
  8. }

A synchronous attempt locks up the browser for a few seconds, and then dumps all the buttons to the screen at once; presumably, because the loop is completes long before the buttons are instantiated. Please correct me if I'm wrong.

  1. // locks up browser for a few seconds, and dumps all buttons to the page at once.
  2. var $pageContent = $('div#pageContent');
  3. for (var count = 0; count < 1000; count++) {
  4.       (function(){
  5.             var myButton = new Button();
  6.             $pageContent.append(myButton);
  7.       }());
  8. }

Thank you for your help.

Sincerely,
Keith :^)

Viewing all articles
Browse latest Browse all 3491

Trending Articles