简体   繁体   中英

Calling class from script generated from CoffeeScript

Not sure what I am doing wrong here but not getting far.

I have created a class using Coffeescript:

# CoffeeScript
App=    
        Title:""
        TopMenu:[]
        AddTopMenu:(title,count,icon)->
            Record=
                Title:title
                Icon:icon
                Count:count                                    
                AddSubMenu:(title,icon,count) ->
                    Title:title
                    Icon:icon 
                    Count:count

Output:

(function() {
  var App;



  App = {
    Title: "",
    TopMenu: [],
    AddTopMenu: function(title, count, icon) {
      var Record;
      return Record = {
        Title: title,
        Icon: icon,
        Count: count,
        AddSubMenu: function(title, icon, count) {
          return {
            Title: title,
            Icon: icon,
            Count: count
          };
        }
      };
    }
  };

}).call(this);

The question is, how to call App.Title or App.AddTopMenu?

I have tried the following:

<script>
  App.Title="asdasd";
</script>
<script>
var test = new App();
test.Title="asdasd";
</script>

Without luck, cannot find App.

Any help would be great.

Paul

Because the script generated by CoffeeScript is wrapped in a IIFE, anything declared inside it is hidden from the outside scope - this means that you need to be very specific about what you expose.

There are a number of ways you can do this, which basically depend on where your script is going to run. You could assign it to window for the browser, or to module.exports for node.js, or use something like Require.js to do your dependency management.

Since it looks like you are going to use this in a browser, you probably want to do something like :

window.App =    
    Title: ""
    TopMenu: []
    AddTopMenu: (title, count, icon)->
        Record =
            Title: title
            Icon: icon
            Count: count                                    
            AddSubMenu: (title, icon, count) ->
                Title: title
                Icon: icon 
                Count: count

which will attach App to the window object so it can be called from other scripts.

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