2012-05-05 12 views
20

Tengo el siguiente código CoffeeScript para generar y cuadro de alerta:Funciones de llamada definidas con script de café?

show_alert =() -> 
    alert("Hello! I am an alert box!") 

que compila a:

(function() { 
    var show_alert; 

    show_alert = function() { 
    return alert("Hello! I am an alert box!"); 
    }; 

}).call(this); 

en mi html Tengo el siguiente

<input onclick='show_alert()' type='button' value='Show alert box' /> 

Sin embargo, no hay alerta cuadro muestra? El siguiente es el código HTML copiado desde el navegador:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
    <head> 
    <title>Test Rails Application</title> 
    <style type='text/css'>.application h1 { 
    color: lime; } 
</style> 
    <script type='text/javascript'>(function() { 
    var show_alert; 

    show_alert = function() { 
    return alert("Hello! I am an alert box!"); 
    }; 

}).call(this); 
</script> 
    </head> 
    <body> 
    <h1>Hello from applicaiton.html.haml</h1> 
    <div class='application'><h1>Hello World</h1> 
<input onclick='show_alert()' type='button' value='Show alert box' /> 
</div> 
    </body> 
</html> 

Por qué no soy capaz de obtener un cuadro de alerta a aparecer?

Respuesta

22

Su problema es que el código javascript generado está en otro ámbito. Usted tiene que resolver este ya sea agregando el parámetro -b al compilador CoffeeScript o exportar su función explícitamente a través de

root = exports ? this 
root.show_alert =() -> alert("Hello! I am an alert box!") 

Para obtener más información sobre el tema de exportación y el alcance echar un vistazo a https://stackoverflow.com/a/4215132/832273

creé un working jsfiddle con el código anterior CoffeeScript

4

en el código coffeescrpt, tratar de salvar la función de ventana: window["show_alert"] = show_alert

+1

jftr creo 'root = exportaciones? esta; root.show_alert = show_alert' es mejor en lugar de acceder directamente a la ventana. Ver http://stackoverflow.com/a/4215132/832273 para más detalles –

+0

@mru, de hecho, gracias – akonsu

+0

@mru javascript siempre es extremadamente confuso para mí. ¿Hay algún sitio o texto de referencia específico que cualquiera de ustedes recomendaría? – rudolph9

-1

<script type="text/javascript"> var show_alert; show_alert = function(){ alert("Hello,this is me!"); } </script> creo que esto está bien.

+0

Las preguntas pertenecían al guión de café. – rudolph9

9

he encontrado dos maneras de resolver este problema primero Añadir @ antes del nombre de la función

@say_hi =() -> 
    $(alert('Hello!!!')) 

SEGUNDO al final del archivo de café añadir

window["say_hi"] = say_hi 
Cuestiones relacionadas