stleary
stleary

Reputation: 422

Trying to dynamically navigate to a new page using dojo

I am new to javascript and dojo, and am trying to write code to navigate to another URL dynamically. This seems easy to do with javascript, but I can't get it to work with dojo/on. Here is my example code. The trivial callback works fine. The dojo/on callback invokes the callback, but the new page never appears. I have to do this dynamically and with dojo because, well just because my project requires it. Anyone know why this is failing and how to make it work?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dojo/dojo.js">
</script>
<script type="text/javascript">
callback = function() {
    window.location.href = "about:blank";
    console.debug("callback invoked"); 
}
function init() {
    var node = dojo.byId("test");
    var childNode = dojo.create("a", { href : "" }, node);
    childNode.innerText = "dojo callback click here"; 
    require(["dojo/on"], function(on){
        on(childNode, "click", callback);
    }); 
}
dojo.ready(init);
</script>
<div id="test">
    <p>
    <a href = "javascript:callback()">trivial callback click here</a>
</div>

Upvotes: 2

Views: 3437

Answers (1)

Phix
Phix

Reputation: 9910

Starting with Dojo 1.7, the AMD loader is the preferred way of using Dojo modules.

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dojo/dojo.js"></script>
    <script type="text/javascript">
    require(['dojo/on', 'dojo/dom', 'dojo/domReady!'], function(on, dom){
        on(dom.byId('theDiv'), 'click', function(){
            alert("Click!") // replace this line with location changes
        })
    })
    </script>
</head>
<body>
    <div id="test">
        <a href="javascript:void(0);" id="theDiv">Click Me</a>
    </div>
</body>
</html>

In this example, the core Dojo.js is loaded (as you requested), but the difference is I used the require method, attaching the click method of dojo/on to the div. Ideally, you would use separate javascript files to dictate the behavior of your page, but for this example, embedding the js into the index page is sufficient.

Using the parser, you can use declarative <script type="dojo/on" data-dojo-event="click">...</script>, but for a variety of reasons you should use programmatic parsing and use javascript files for maximum efficiency.

In addition, defining functions/methods/variables in the global scope:

<script type="text/javascript">
callback = function() {
    window.location.href = "about:blank";
    console.debug("callback invoked"); 
}
</script>

... isn't recommended and there are better alternatives.

Upvotes: 4

Related Questions