CoffeeScript將在方法內聲明的變量包裝在對象文字中。如何避免CoffeeScript方法變量被對象字面值包裝?
所以,這樣的:
@Templates =
get: (templateName) ->
result: '' # DECLARED HERE
$.ajax(
'Views/Templates/' + templateName + '.html',
type: 'GET'
dataType: 'html'
success: (data) ->
result = data # ASSIGNED HERE
async: false
)
return result # RETURNED HERE
變爲這樣:
(function() {
this.Templates = {
get: function(templateName) {
({
result: '' //DECLARED IN AN OBJECT LITERAL - I DON'T WANT THIS
});
$.ajax('Views/Templates/' + templateName + '.html', {
type: 'GET',
dataType: 'html',
success: function(data) {
var result; //DECLARED LOCAL TO THE CALLBACK - I DON'T WANT THIS
return result = data;
},
async: false
});
return result; //RETURNED HERE - UNASSIGNED
}
};
}).call(this);
但我需要什麼,這對我的作品,是這樣的:
(function() {
this.Templates = {
get: function(templateName) {
var result = '' //DECLARED HERE
$.ajax('Views/Templates/' + templateName + '.html', {
type: 'GET',
dataType: 'html',
success: function(data) {
return result = data; //ASSIGNED HERE
},
async: false
});
return result; //RETURNED HERE
}
};
}).call(this);
我在做什麼錯誤?我怎樣才能解決這個問題?
這並不是一個封閉它的對象文本和它包裹着的括號以使得它不會作爲一個塊 – Esailija 2012-02-21 15:26:55
同步GET可以治療嗎?這可能不是一個好主意。 – loganfsmyth 2012-02-21 15:37:23
我忘了提及我是CoffeeScript和Javascript的新手。感謝所有的答案和提示。 – 2012-02-22 18:06:25