pvitt
pvitt

Reputation: 1075

using named function for onclick of dijit menu item

Im having problem calling an onClick function for a dijit menu item. I keep getting that the function is undefined:

Here is code for the menu item:

...
<div data-dojo-type="dijit/DropDownMenu" id="fileMenu">
            <div data-dojo-type="dijit/MenuItem" data-dojo-props="onClick:function(){SetPage('test');}">Watershed</div>
        </div>

and here is the function I'm trying to call:

function SetPage(pg){
alert(pg);
}

do I have to register the onclick event in code?

Thanks

Upvotes: 0

Views: 584

Answers (2)

mannyyysh
mannyyysh

Reputation: 339

this is the issue because of scope as setpage is not in the scope of onclick function of menu you can call directly alert function inside this like below:

<div data-dojo-type="dijit/DropDownMenu" id="fileMenu"> <div data-dojo-type="dijit/MenuItem" data-dojo-props="onClick:function(){alert('test';}">Watershed</div> </div>

or you can do attach a event handler here:

<div data-dojo-type="dijit/DropDownMenu" id="fileMenu"> <div data-dojo-type="dijit/MenuItem" data-dojo-props="onClick:_onClick">Watershed</div> </div>

and in your javascript file

_onClick:function(evt){this.SetPage(evt);}, SetPage:function(evt){ alert(evt.target.innerHTML);}

Upvotes: 2

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44757

This sounds like a scoping issue. Even when a function is named, it should be available in the global scope to be able to make it work with declarative code.

For example, if you put that function inside a require() block, it will not work, since it is scoped to that function only (it's only visible from inside).

For example:

require(["dijit/MenuItem", "dijit/DropDownMenu", "dojo/parser"], function() {
  function SetPage(pg) {
    alert(pg);
  };

  SetPage("test"); // This will work because it's in the same scope
});

SetPage("test"); // This will not work

The lower SetPage() call has another scope, so it can't see the function. To solve the issue, the function has to be defined on the global scope (which is window for web applications).

A possible solution would be:

require(["dijit/DropDownMenu", "dijit/MenuItem", "dojo/parser"], function() {
  window.SetPage = function(pg) {
    alert(pg);  
  }; 
});

This will work, because you add it to the window object. You can see an example of this on JSFiddle.

Upvotes: 1

Related Questions