简体   繁体   中英

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?

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

Try using this converter:

http://js2coffee.org/

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM