Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails, getting syntax error with coffee script

i am trying to do an autocomplete feature in rails using the jquery ui library. however i keep getting syntax errors "Syntax Error: reserved word "function" on line ..."

this is my lessons.js.coffee file

jQuery ->

$(function() {
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#lesson_tag_name" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: $('#lesson_tag_name').data('autocomplete-source')
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
});

i read online somewhere that i could replace the word function with -> i did that and i stopped receiving the function errors, but then i get other syntax errors such as "Syntax Error: reserved word "var" on line..."

am i doing something wrong?

like image 953
Sasha Avatar asked Apr 17 '12 09:04

Sasha


2 Answers

Only the first line is coffeescript; the rest is normal javascript.

Try using this converter:

http://js2coffee.org/

$(function() {}); becomes $ ->

like image 123
DanS Avatar answered Nov 18 '22 11:11

DanS


If you want to embed javascript within a coffeescript file, you can do so using backticks:

jQuery ->
  `function abc() { return 123; }  // js syntax here`

See here: http://coffeescriptcookbook.com/chapters/syntax/embedding_javascript

This is pretty confusing, though, so it is generally a better idea to convert the code to coffeescript, in which case you can use the js2coffee.org converter as DanS suggested.

like image 21
Dillon Kearns Avatar answered Nov 18 '22 11:11

Dillon Kearns