rails, getting syntax error with coffee script

北城余情 提交于 2019-12-21 04:16:21

问题


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?


回答1:


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

Try using this converter:

http://js2coffee.org/

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




回答2:


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.



来源:https://stackoverflow.com/questions/10188363/rails-getting-syntax-error-with-coffee-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!