我有一个用CoffeeScript编写的非常简单的程序,如果用户点击按钮,则应在控制台中显示一个值。以下是我的代码:
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id='butn'>click here</button>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js是已编译的CoffeeScript。我的CoffeeScript如下:
init.coffee
init = =>
game = new Game()
# Start it all off
$(document).ready(init)
class Game
constructor: () ->
@UI = new UI()
class UI
constructor: () ->
@toolbar = new Toolbar('foo')
class Toolbar
constructor: (@value) ->
@clickhandler()
clickhandler: () =>
$('body').on 'click', '#butn', ->
console.log 'Value = ', @value
Compiled JS是:
// Generated by CoffeeScript 1.3.3
(function() {
var Game, Toolbar, UI, init,
_this = this,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
init = function() {
var game;
return game = new Game();
};
$(document).ready(init);
Game = (function() {
function Game() {
this.UI = new UI();
}
return Game;
})();
UI = (function() {
function UI() {
this.toolbar = new Toolbar('foo');
}
return UI;
})();
Toolbar = (function() {
function Toolbar(value) {
this.value = value;
this.clickhandler = __bind(this.clickhandler, this);
this.clickhandler();
}
Toolbar.prototype.clickhandler = function() {
return $('body').on('click', '#butn', function() {
return console.log('Value = ', this.value);
});
};
return Toolbar;
})();
}).call(this);
控制台上未显示值'foo'。控制台记录“Value =”但不记录“foo”。请有人帮我理解为什么以及如何在不改变我的程序的情况下解决这个问题。
感谢您的帮助。
答案 0 :(得分:2)
您的问题是事件处理程序中this
keyword的值,它指向DOM元素而不是工具栏实例。使用function binding:
class Toolbar
constructor: (@value) ->
@clickhandler()
clickhandler: () ->
$('body').on 'click', '#butn', =>
console.log 'Value = ', @value