好的,所以我很难让事件绑定与 Coffeescript 和 Backbone 一起工作。我觉得这与我如何初始化所有内容有关。我觉得事件委托甚至都没有运行。
这是我的视图代码:
$ ->
class AppName.TitleView extends Backbone.View
template: JST['templates/title']
collection: new AppName.Members
events:
"keypress #search" : "search",
initialize: =>
$('#search').keypress(@search) #doing it manually as a hack
search: ->
console.log('search handler call')
render: =>
$('#app').html(@template)
@delegateEvents() #this doesn't seem to do anything, nor does @delegateEvents(@events)
@
编译时,它看起来像这样:
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
$(function() {
AppName.TitleView = (function(_super) {
__extends(TitleView, _super);
function TitleView() {
this.render = __bind(this.render, this);
this.initialize = __bind(this.initialize, this);
TitleView.__super__.constructor.apply(this, arguments);
}
TitleView.prototype.template = JST['templates/title'];
TitleView.prototype.collection = new AppName.Members;
TitleView.prototype.events = {
"keypress #search": "search",
};
TitleView.prototype.initialize = function() {
return $('#search').keypress(this.search);
};
TitleView.prototype.search = function() {
console.log('search handler call'););
});
};
TitleView.prototype.render = function() {
$('#app').html(this.template);
this.delegateEvents();
return this;
};
return TitleView;
})(Backbone.View);
});
}).call(this);
AppName.TitleView
从我的路由器(又由 main 启动app.coffee
)启动:
$ ->
class AppName.Router extends Backbone.Router
routes:
".*": "main"
main: ->
@titleView ||= new AppName.TitleView el: $('#app')[0]
@titleView.render()
但是对于我的生活,我无法#search
从 Backbone Events 绑定到绑定。我的 hack(在代码中)只是通过initialize
函数中的 jQuery 进行绑定。
知道发生了什么吗?我希望这是一个简单的错字或错误的初始化。