CoffeScript code:
department = ->
console.log 1
This compiles into js code :
// Generated by CoffeeScript 1.6.3
(function() {
var department;
department = function() {
return console.log(1);
};
}).call(this);
And I have a button :
<button onclick = "department()" >add department</button>
But when I click it it throws an error:
Uncaught ReferenceError: department is not defined
So what should I do?
It is because your function department
is not in the global scope, instead it is in a closure of your anonymous function that you have written as IIFE.
<button onclick = "department()" >add department</button>
when clicked will look for the function department()
in the global scope and you don't have it there.
This is what happens when you have handlers written as inline html attributes. You can bind the event using javascript giving the function as reference within your closure.
You could do:
Example:-
<button id="dept" >add department</button>
and
(function() {
var department;
department = function() {
return console.log(1);
};
window.onload = function(){
document.getElementById('dept').onclick = department;
}
}).call(this);