我有以下代码
define [
"jquery",
"backbone",
"underscore",
"models/days"
], ($, Backbone, _, days) =>
class Calendar extends Backbone.View
el : "#calendar_box"
collection : days
display: =>
@collection.fetch_data
month :8
year :2012
, @render
render: =>
# console.log @collection - gives "undefined"
console.log @ # this returns "Window" instead of "Calendar" - current obj.
# return the calendar object
new Calendar()
这是Coffeescript中的BackboneView,它要求服务器将给定月份和年份的日期作为日历。
数据返回正常,因为我可以在Chrome控制台中检查它 - GET请求及其响应。
但是,在“渲染”功能中,看起来“@”处于全局级别,而不是“日历”级别。
这里发生了什么?
答案 0 :(得分:1)
检查binding this上的backbone.js文档,然后在您的日历中添加一个初始化函数,并使用下划线bindAll
-function绑定渲染和其他方法以获得正确的上下文
NOT COFFEESCRIPT:
initialize: function() {
_.bindAll(this, 'render', 'display');
}
希望这有帮助!
答案 1 :(得分:1)
我通过改变
解决了这个问题($, Backbone, _, days) =>
到
($, Backbone, _, days) ->
这似乎有效。
答案 2 :(得分:1)
澄清为什么改变脂肪箭头=>细箭头 - >因为Coffeescript编译器故意在这两者之间产生歧视。
简而言之:胖箭头在外部范围内创建对this
关键字的引用,并使@
符号引用外部this
< / p>
# Coffeescript
fatArrow => @
thinArrow -> @
现在编译好的Javascript:
// make a reference to the 'this' keyword (might be the global scope)
// for the @ symbol inside the fat arrow function
var _this = this;
fatArrow(function() {
// the @ symbol does not actually reference 'this'
// but the outer scope _this variable
return _this;
});
thinArrow(function() {
// the @ symbol in a thin arrow function
// is the same as the 'this' keyword in javascript
return this;
});
javascript中的许多模式都需要引用外部作用域,通常称为self
或Coffeescript _this
。例如,在事件回调中,常见于jQuery等框架中。 Coffeescript使这很简单,因为您可以使用胖箭头而不是使用外部范围this
引用来混乱您的代码。
# Coffeescript
initializeFatGuy = ->
@eat = (food) -> alert 'eating some #{food}'
# common example of event callback with double arrow
$('body').on 'click', (event) =>
# call the eat method
# @ is the outer scope _this variable generated by Coffeescript
@eat 'chips'