user2950593
user2950593

Reputation: 9627

CoffeeScript doesn't work onclick

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?

Upvotes: 1

Views: 1501

Answers (3)

Mathias L&#248;ken
Mathias L&#248;ken

Reputation: 11

Old post, but if anyone happens to stumble upon this like I did...

Simply add --bare as an argument when compiling to not wrap the code in an anonymous function.

Then instead of calling CoffeeScript directly, we just use the compiled js file, like if you wrote it in JS yourself.

<button onclick="getCoffee()">From CoffeeScript</button>
<script type="text/javascript" src="Resources/js/getcoffee.js"></script>

Don't need anything special in your CoffeeScript this way.

getCoffee = () ->
  alert "Delicious Coffee..."

Upvotes: 1

Johnny
Johnny

Reputation: 1383

window.department = ->
    console.log 1

window before any coffeescript function will make it global

also

@window.department = ->
    console.log 1

the @ symbol refers to this which in this case refers to the document.

Upvotes: 1

PSL
PSL

Reputation: 123739

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);

Upvotes: 7

Related Questions