Rockbot
Rockbot

Reputation: 973

Scope in Coffeescript / Rails

When I do something simple like this:

$ ->
  $('#target').html('blabla')

it works.

When i try:

$ ->
  $('#target').html('blabla').myFunction()

  myFunction = ->
    // a certain action

I always get an error: TypeError: $(...).html(...).myFunction is not a function.

Why is that?

As you might guess, I´m far from pro!

Upvotes: 2

Views: 222

Answers (2)

Jasper Kennis
Jasper Kennis

Reputation: 3062

It's not a CoffeeScript problem. You're not defining a jQuery plugin that can be called on a jQuery object, but just a regular function. Have a look here: http://docs.jquery.com/Plugins/Authoring

Upvotes: 1

rorra
rorra

Reputation: 9693

If you do something like this:

$ ->
  $('#target').html('blabla').myFunction()

  myFunction = ->
    alert("OK")

is transformed to this:

$(function() {
  var myFunction;
  $('#target').html('blabla').myFunction();
  return myFunction = function() {
    return alert("OK");
  };
});

And as you can see, myFunction is a variable that contains some structure, but the object that is returned when you do $('#target'#).html('blablabla') doesn't have a method named myFunction and that's the reason you get that error.

I'm not sure what you are trying to do, but you can do something like

$ ->
  myFunction = (data) ->
    alert(data)

  myFunction $('#target').html('blablabla')

which is transformed to:

$(function() {
  var myFunction;
  myFunction = function(data) {
    return alert(data);
  };
  return myFunction($('#target').html('blablabla'));
});

If you are learning coffeescript, a good website to have in mind for transformation is http://js2coffee.org/

Upvotes: 4

Related Questions