나는 Revealing Module Pattern을 사용하는 작은 스크립트를 만들고 있습니다.자바 스크립트 모듈 패턴 및 Coffeescript 공개
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
}
}();
는 커피 스크립트에서이 동일 :
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
init
및 changeColor
는 전역 범위에 노출되고, 자바 스크립트가 잘 작동하지만 커피 스크립트의 일이 있기 때문에 실패 init 메소드가 없다.
이 공개 모듈 패턴을 CoffeeScript로 변환하려면 어떻게해야합니까?
나는 또한 더 나은 방법에 대한 제안이 열려 있습니다. 당신이 그 방법을 노출하는 새로운 JSON 개체를 반환하려면 ;-)
덕분에, 도미니크
는
'while' 루프와'수동 i' 증가를 사용할 필요가 없습니다; [0 ... 크기]에서'for i '를 사용하십시오. –