Search code examples
javascriptdojodom-events

How can I make a data-dojo-attach-event run?


I am trying to run the event after adding a domNode programatically as such:

<a href="javascript:void(0)" data-dojo-attach-event="click:openRegistration">Register</a>

This event is not parsed by Dojo when the page is first loaded because it is being added later on. Even after running

parser.parse();

The event does not run. How can I make this event run?


Solution

  • You don't want the dojo parser to parse the page twice: it would redundantly parse and create things that were already created and cause a mess. To add a node programmatically after the page has been parsed, have a look at dojo/dom-construct.

    require(["dojo/dom-construct", "dojo/domReady!"],
        function(domConstruct) {
    
            var openRegistration = function() {
                alert("foo");
            }
    
            domConstruct.create("a", {
                innerHTML: "Register",
                click: openRegistration,
                href: "javascript:void(0)"
            }, document.body);
        });
    

    Replace document.body with a reference to the parent node where you want to insert the node, and look at the 3rd parameter for placement options.