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

前端 未结 3 1180
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 17:38

We want to develop a browser (client side only) library using Coffeescript, and in particular, we tend to use the \"class\" capability of Coffeescript quite a bit, in addition t

相关标签:
3条回答
  • 2021-01-30 18:23

    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!

    0 讨论(0)
  • 2021-01-30 18:24

    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!

    0 讨论(0)
  • 2021-01-30 18:29

    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.

    0 讨论(0)
提交回复
热议问题