Expose a javascript api with coffeescript

前端 未结 2 818
梦毁少年i
梦毁少年i 2020-12-31 07:36

I recently started using coffeescript and was curious what is the \"right\" way to expose an object that I create with Coffeescript to other javascript pages. Because of co

相关标签:
2条回答
  • 2020-12-31 08:19

    Yep that's correct. Alternatively you can use define @myApi = { foo: -> } because this is window in the root context of the file.

    0 讨论(0)
  • 2020-12-31 08:32

    You can simplify the syntax further, for example if you had 2 internal functions

    example.coffee

    myPrivateFunction = ->
        "return 1"
    
    myPrivateFunction2 = ->
        "return 2"
    
    @myApi = {
        myFunction : myPrivateFunction,
        myFunction2 : myPrivateFunction2
    }
    

    example.js

    this.myApi = {
      myFunction: myPrivateFunction,
      myFunction2: myPrivateFunction2
    };
    

    The @ will be window within the main scope of the file.

    Then call from elsewhere by window.myApi.myFunction()

    If you wanted to map the external function names to the same internal names, if you don't specify key : value pairs, it will just use the string value as the key by default.

    example.coffee

    @myApi = {
        myPrivateFunction,
        myPrivateFunction2
    }
    

    example.js

    this.myApi = {
      myPrivateFunction: myPrivateFunction,
      myPrivateFunction2: myPrivateFunction2
    };
    
    0 讨论(0)
提交回复
热议问题