Using RequireJS for Recursive Map

115 Views Asked by At

I'm using requireJS for my web application, and I'm stumped on how to use requireJS to build a recursive map of the same object. For example, my object is called 'section', and I want to create a child below each using the same object:

Section
  > Section
    > Section
        > (etc...)

Here is the contents of section.js:

define(['jquery'], function($) { 
  children = [];  

  function init() {
    require(['jquery', 'section'], function($, section) {
      children.push(section.init(mediator, this));
    });

    return children;
  }

  return {
    init: init
  }
}

This has resulted in a self-referencing mess. I don't know how I can create a new instance of section for the new, child section.

1

There are 1 best solutions below

0
On

This is probably something that can be done without changing the RequireJS parts. Is the idea to create a reference to self, similar to window.self?

function Section() {
    this.children = [];
}
var section = new Section();
section.children.push(section);

If each Section has a child that is a new Section, unless it's generated on demand, the code will loop infinitely constructing Section after Section.