سؤال

i have

class Main
   test:->
      alert "yay!"

in coffeescript, and i want to run that inside my index.html

<script>
    $(function(){
        //and obv Main.test(); doesn't work
    });
</script>

there is a note of this on the website, it says it wouldn't work. But I couldn't find how to make it work. any ideas? i need to find out what coffeescript closure wrapper is.

or does coffeescript execute after document.ready anyway?

thx!

هل كانت مفيدة؟

المحلول

class Main

Try class @Main instead.

obv Main.test(); doesn't work

Right. Should be new Main().test() or Main::test().

does coffeescript execute after document.ready anyway?

Assuming that you're executing it via extras/coffee-script.js and using jQuery, yes.

نصائح أخرى

To execute Coffeescript after document.ready you can use jQuery like this:

$ ->
  # Put your function code here
  init()

What that is doing is running jQuery(function () { callback... }) like the 3rd section at this link: http://api.jquery.com/jQuery/

Which basically says this:

jQuery( callback ) Returns: jQuery Description: Binds a function to be executed when the DOM has finished loading.

I declare all my classes, etc outside of document ready and then call an init function to get it running at the appropriate time.

I hope that helps!

Coffeescript wraps your code in a function call so you can't accidentally overwrite global variables.

If you want any variables, functions or classes to be global (so they can be accessed by other files), you need to explicitly make them global by attaching them to this or window.

# Stays within the function scope, so you can't access it outside the file
myNotGlobalFunction -> return

# Attaches it to `this` aka `window`, so can be accessed globally
this.myGlobalFunction -> return

# A shortcut using @ which is an alias to `this.`
@myOtherGlobalFunction -> return

This compiles to:

(function() {
  myNotGlobalFunction(function() {
    return;
  });
  this.myGlobalFunction(function() {
    return;
  });
  this.myOtherGlobalFunction(function() {
    return;
  });
}).call(this);

I've run into this issue before as well. First of all, since you are defining a class, you need to instantiate it. Then you can call you test function on the instance:

<script>
    $(function(){
        var an_instance_of_main = new Main();
        an_instance_of_main.test();
    });
</script>

However, you might have noticed that the browser can't find your Main class. This is because when the CoffeeScript is compiled, it wraps a self-executing function around your class definition in order to prevent Main from being globally accessible. If you want to make it globally accessible, you can prefix it with window:

class window.Main
   test:->
      alert "yay!"

or assign it after defining it:

class Main
   test:->
      alert "yay!"

window.Main = Main
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top