Example of using Coffeescript classes and RequireJS (or Curljs or similar) for client side browser library

偶尔善良 提交于 2019-12-02 15:52:15

First off, if you're using RequireJS you're going to have a not-easy time returning multiple "things" from a define function. RequireJS uses AMD (!NOT! CommonJS) format "standards", which doesn't contain a module.exports object for exporting "stuff" but instead relies on return something.

With that said, I'm not exactly sure what you're looking for here but having a class work with RequireJS is pretty easy. Something like this:

define ['my/required/module'], (myModule) ->
    class MyOtherModule
        privateField = 0

        constructor: ->
        publicMethod: ->

    return MyOtherModule

This can be used in a require/define function just like any other script. Take this example:

require ['my/other/module'], (MyOtherModule) ->
    instance = new MyOtherModule()

We can even use it with "extends"

define ['my/other/module'], (MyOtherModule) ->
    class MyThirdModule extends MyOtherModule
        ...   

Hopefully this helps!

I'm using coffee-toaster too, and I found few posts recently.
I thought that was worth to read, maybe we could work it out:

http://blog.toastymofo.net/2012/04/coffeescript-requirejs-and-you-part-one.html
http://24ways.org/2012/think-first-code-later/

and http://jamjs.org seems pretty cool!

I haven't actually used this technique yet, but:

The only thing to keep in mind here is that CoffeeScript statements are also return values when they are last in a function. So, basically, the following code:

define [], () ->
  class Main

translates to:

define([], function() {
  var Main;
  return Main = (function() {

    function Main() {}

    return Main;

  })();
});

and that should work as expected (I see no reason why it wouldn't based on the compiled JavaScript).

For managing code base, I believe the CS plugin should come in handy. It's maintained by James Burke himself, and supports building of CoffeeScript projects the same way JavaScript projects are built.

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