Correctly creating and calling Coffeescript functions in Rails -
i using function return unique values of array.
function unique(array) { return $.grep(array, function(el, index) { return index == $.inarray(el, array); }); }
it works when it's placed in script block of view call this:
$('#array_text').val(unique(coldata).join('; '));
however, when "translate" coffeescript , place in relevant coffeescript file
unique = (array) -> $.grep array, (el, index) -> index $.inarray(el, array)
although function appears rendered correctly in associated .js file,
var unique; unique = function(array) { return $.grep(array, function(el, index) { return index === $.inarray(el, array); }); };
i error when call unique same way view's script block.
uncaught referenceerror: unique not defined
i expected unique()
"global" function in environment.
every javascript function defined in coffee script file in rails scoped local file, isn't visible outside file default. if want use function globally have define @
sign @ beginning.
@unique = (array) -> $.grep array, (el, index) -> index $.inarray(el, array)
and can use everywhere , code in script block should work again.
Comments
Post a Comment