Search code examples
parsingdynamicdojodigit

Dynamic Content Loading - HTML5 is OK, Dojo is not


I've got a situation where I am loading DIV's dynamically from a server with dojo.xhrGet. All that is fine. The content comes back fine, and the DIV is inserted into the page fine. Note that in this situation, I cannot know the DIV to load prior to some other event occurring.

The problem seems to be that DIJIT widgets contained within the dynamic DIVs aren't DIJIT widgets, but run-of-the-mill HTML widgets. That is, I can work on them using "dojo.byId('widgetID')" and use standard JavaScript, but if I try "registry('widgetID')", I get an "undefined" response.

How can I get dynamically loaded and otherwise declarative DIV code to be parsed into true DIJIT widgets?


Solution

  • You need to use dojo/parser after your markup div has been loaded to your DOM. The function parse() will transform your HTML markup from div to a dijit widget if the markup has been decorated properly.

    By the way dojo.xhrGet is Deprecated and you should use dojo/request/xhr instead.

    Below and example with some pseudocode:

    require(["dojo/request/xhr", "dojo/dom-construct"], function(xhr, domConstruct){
      xhr("example.json", {
        handleAs: "text" // or whatever
      }).then(function(data){
        // place your div to the dom (data is an html markup similar to this <input data-dojo-type="dijit/form/TextBox" type="text" name="dept1" />)
        var targetDom = 'targedDom';
        domConstruct.place(data, targetDom, 'replace');
        // trasform your div to a dijit widget 
        parser.parse(dojo.byId(targetDom)).then(function(){
            // after is parsed do smt here
        });
    
      }, function(err){
        // handle the error condition
      }, function(evt){
        // handle a progress event from the request if the browser supports XHR2
      });
    });