0

I am using this function to return the unique values of an array.

function unique(array) {
    return $.grep(array, function(el, index) {
        return index == $.inArray(el, array);
    });
}

It works perfectly when it's placed in the script block of the view where I call it like this:

$('#array_text').val(unique(colData).join('; '));

However, when I "translate" it to Coffeescript and place it in the relevant coffeescript file

unique = (array) ->
  $.grep array, (el, index) ->
    index is $.inArray(el, array)

although the function appears to be rendered correctly in the associated .js file,

 var unique;

  unique = function(array) {
    return $.grep(array, function(el, index) {
      return index === $.inArray(el, array);
    });
  };

I get an error when I call unique the same way from the view's script block.

Uncaught ReferenceError: unique is not defined 

I expected unique() to be a "global" function in the environment.

Community
  • 1
  • 1
JHo
  • 1,068
  • 1
  • 14
  • 29

1 Answers1

1

Every javascript function defined in coffee script file in rails is scoped only to local file, so it isn't visible outside the file by default. If you want to use your function globally you have to define it with @ sign at the beginning.

@unique = (array) ->
  $.grep array, (el, index) ->
    index is $.inArray(el, array)

And now you can use it everywhere and you code in script block should work again.

edariedl
  • 3,234
  • 16
  • 19