Galatoni
Galatoni

Reputation: 68

Can't use dojo/query unless its in global

This is actually my first question in Stack (long time listener and all that).

I'm fairly new to Javascript in general and certainly new to Dojo. Been racking my brains for ages on this, but can't see what i'm doing wrong.

I'm trying to get query to work through this code to return all the <p> tags in the DOM. All well and good.

define ([
"dojo/dom",
"dojo/query"
], function (dom) {
return {
    changeParagraphs: function() {
        var nodeList = dom.query('p');
        console.log(nodeList);
    }
   }
});

Excuse the layout, still getting used to this. If I call query as I have here...

require(["custom/q3",
         "dojo/domReady!",
         "dojo/query"], function(myObject){
    myObject.changeParagraphs();
})

I get an object has no method query error.

If instead of

var nodeList = dom.query('p')

I call...

var nodeList = dojo.query('p')

All is well. Why? I know its bad practice to use global (in any language really), but what is it i'm doing wrong? I've no intention of using global!

I imagine i'm most likely wasting people's time here, but I've been banging my head against the keyboard for hours now. It's mostly likely something really obvious!

Thanks in advance!

Upvotes: 0

Views: 69

Answers (1)

BuffaloBuffalo
BuffaloBuffalo

Reputation: 7852

The error object has no method query is a hint as to the problem. The dojo/dom module has no query method. Instead, you need to expose the dojo/query method in your define function callback:

define(["dojo/dom", "dojo/query"], function (dom, query) {
    return {
        changeParagraphs: function () {
            var nodeList = query('p');
            console.log(nodeList);
        }
    }
});

Then in your require:

require(["custom/q3", "dojo/domReady!"], function (myObject) {
    myObject.changeParagraphs();
})

Upvotes: 2

Related Questions