That's because the func()
function is locally scoped in the require()
callback function. This means that you cannot see it, unless you're calling the function from inside the require()
callback.
However, an onclick attribute can only access the global scope, so in your current situation it can not execute func()
, that's why it's giving the error that it's not defined.
To solve this, you can do two things:
- Move your
func()
to global scope - Move your event handling to the local
require()
scope
Move your func()
to global scope
To move your function to the global scope, you should rewrite your function as:
func = function(no){
alert('seq:'+no);
}
Because there is no var
in front of it, it's actually being applied to the global scope. You could also write the following:
window.func = function(no){
alert('seq:'+no);
}
This is the easiest solution, but also the most ugly one. Usually it's recommended to use the global scope as less as possible, and in this case it's not really necessary.
Move your event handling to the local require()
scope
A better solution (I think) is to move your event handling into the same local scope as your function is in. However, in order to do that, you cannot use the same strategy you're using now. You will have to replace your output
DOM string by constructing proper DOM nodes using the dojo/dom-construct module.
For example:
var table = domConstruct.create('table', {
class: "output",
cellspacing: 0,
cellpadding: 0,
border: 1
});
domConstruct.place('<thead>' +
'<tr><th>NO</th><th>NAME</th><th>FORM</th><th>DESCRIPTION</th><th>WRITER</th>' +
'</tr>' +
'</thead>', table);
var body = domConstruct.create("tbody");
arrayUtil.forEach(data, function(item,i){
var row = domConstruct.create("tr");
domConstruct.place('<td>'+item.seq+'</td>', row);
domConstruct.place('<td>'+item.name+'</td>', row);
var cell = domConstruct.create('td');
domConstruct.place(cell, row);
var link = domConstruct.create("a", {
href: "#",
innerHTML: item.form
});
on(link, "click", function() {
func(item.seq);
return false;
});
domConstruct.place(link, cell);
domConstruct.place('<td>'+item.desc+'</td>', row);
domConstruct.place('<td>'+item.writer+'</td>', row);
domConstruct.place(row, body);
});
domConstruct.place(body, table);
domConstruct.place(table, resultDiv);
This piece of code replaces your entire DOM construction. It creates DOM nodes and uses the dojo/on module to add the func
function as event handler for the onClick event.
I also made a JSFiddle that demonstrates this solution.
This has several benefits:
- Your
func()
is only available where it has to be available. Nobody can override it by using a variable with the same name in the global scope. - You can see I'm using less HTML code in the JavaScript part and I have less JavaScript functions in the HTML part (the
onclick
attribute is no longer necessary). If you improve this even further you can decouple the HTML code and the JavaScript code, improving the structure of your application.