Javascript揭示模块模式和Coffeescript

时间:2011-11-27 20:05:46

标签: javascript module design-patterns coffeescript

我正在处理一个使用Revealing Module Pattern的小脚本。

使用goold ol'Javascript一切正常,但我想知道如何将其转移到Coffeescript。

以此为例:

// revealing module pattern
var anchorChange4 = function () {

    // this will be a private property
    var config = {
        colors: [ "#F63", "#CC0", "#CFF" ]
    }

    // this will be a public method
    var init = function () {
        var self = this; // assign reference to current object to "self"

        // get all links on the page
        var anchors = document.getElementsByTagName("a");
        var size = anchors.length;

        for (var i = 0; i < size; i++) {
            anchors[i].color = config.colors[i];

            anchors[i].onclick = function () {
                self.changeColor(this, this.color); // this is bound to the anchor object
                return false;
            };
        }
    }

    // this will be a public method
    var changeColor = function (linkObj, newColor) {
        linkObj.style.backgroundColor = newColor;
    }

    return {
        // declare which properties and methods are supposed to be public
        init: init,
        changeColor: changeColor
    }
}();

在Coffeescript中等于此:

anchorChange4 = ->
  config = colors: [ "#F63", "#CC0", "#CFF" ]
  init = ->
    self = this
    anchors = document.getElementsByTagName("a")
    size = anchors.length
    i = 0

    while i < size
      anchors[i].color = config.colors[i]
      anchors[i].onclick = ->
        self.changeColor this, @color
        false
      i++

  changeColor = (linkObj, newColor) ->
    linkObj.style.backgroundColor = newColor

  init: init
  changeColor: changeColor

initchangeColor暴露在全局范围内,Javascript工作正常,但CoffeeScript事情失败,因为它没有'init'方法。

将此揭示模块模式转换为CoffeeScript需要做些什么?

我也愿意就如何改善它提出建议。 ; - )

谢谢, 多米尼克

2 个答案:

答案 0 :(得分:2)

CoffeeScript和JavaScript版本之间的区别在于,从不调用CoffeeScript版本中定义的函数。在JS版本中,函数的返回值被放在anchorChange4中,但在CS版本中,变量自身获取函数。

您可以通过在CoffeeScript代码的第一行和最后一行添加一些括号来更改此项:

anchorChange4 = (->
    ...
    changeColor: changeColor)()

答案 1 :(得分:1)

如果要返回一个暴露这些方法的新JSON对象,那么最后一行应该是......

{
  init: init
  changeColor: changeColor
}

返回JSON对象而不仅仅是changeColor。请记住,coffee从函数返回最后一个执行语句,你有两行你想要返回。

相关问题