Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

javascript - Multiple Files communication with coffeescript

When I create a new coffeescript file, I cannot access the code in the compiled code from another file because it gets wrapped in some function scope. For example:

CoffeeScript:

class ChatService
  constructor: (@io) ->

Generated Javascript:

(function() {
  var ChatService;    
  ChatService = (function() {    
    function ChatService(io) {
      this.io = io;
    }    
    return ChatService;    
  })();    
}).call(this);

When trying to call ChatService in another file, it's not defined. How do I handle multiple files with coffeescript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Depending on whether this is client- or server-side code, there are two slightly different approaches.

Client-side: Here we attach things that should be available across files to the global namespace (window) as follows:

class window.ChatService
  constructor: (@io) ->

Then, in another file both ChatService and window.ChatService will allow access to the class.


Server-side: Here we must use exports and require. In the ChatService.coffee file, you would have the following:

class exports.ChatService
  constructor: (@io) ->

Then, to get at it from another file you can use:

ChatService = require('ChatService.coffee').ChatService

Note: If there are multiple classes that you are getting from ChatService.coffee, this is one place where CoffeeScript's dict unpacking really shines, such as:

{ChatService, OtherService} = require('ChatService.coffee')

Both: Basically, we choose whether to run server-side or client-side code based on which environment we're in. A common way to do it:

class ChatService
  constructor: (@io) ->

if typeof module != "undefined" && module.exports
  #On a server
  exports.ChatService = ChatService
else
  #On a client
  window.ChatService = ChatService

To get it:

if typeof module != "undefined" && module.exports
  #On a server
  ChatService = require("ChatService.coffee").ChatService
else
  #On a client
  ChatService = window.ChatService

The else clause of the second block can be skipped, since ChatService already refers to the reference attached to window.

If you're going to define a lot of classes in this file, it may be easier to define them like:

self = {}

class self.ChatService

And then attach them like module.exports = self on the server and _.extend(window, self) on the client (replace _.extend with another extend function as appropriate).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...