4

I am starting with rails and coffeescript, but I am having a strange issue now. I would like to create a function called log, which I created like this in my .coffee:

log = (message) -> console.log message

It it translated to js like this:

(function() {
  var log;

  log = function(message) {
    return console.log(message);
  };

  log('Podcast downloader 2000');

}).call(this);

If I call the function as I am calling in the example, it works. but now I want to call it using a onclick="log('avb')

<span onclick="log('abc')"/>

but the function is not on the right scope, so it doesn't get called.

How do I change my code so I can call the function from the onclick attribute?

thanks!

JSBach
  • 4,679
  • 8
  • 51
  • 98

1 Answers1

4

as suggested by Sterling in the comment section, it's not good practice to use onclick but if you really need to do this, place the function in the global namespace

window.log = (message) -> console.log(message)

in cases like this, it's better to create a namespace for the app and add functions there.

@MyNamespace = {}

class MyNamespace.CommonFunctions
  @log = (message) -> console.log(message)

Then in your view

<span onclick='MyNamespace.CommonFunctions.log("abc")'>

This keeps things organized and you don't clog the global namespace.

LISTENER APPROACH

A better way to do this is to use event listeners (using jquery).

# view
<span class='msg'></span>

# js
log = (message) -> console.log(message)

$('.msg').on 'click', -> log('abc')
jvnill
  • 29,479
  • 4
  • 83
  • 86