好的,所以我在获取事件绑定与Coffeescript和Backbone一起工作时遇到了一些困难。我有一种感觉,它与我如何初始化一切有关;我觉得事件代表团甚至没有运行。似乎无法正确绑定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
从我的路由器拉开序幕(后者又被拉开序幕主要app.coffee
)与:
$ ->
class AppName.Router extends Backbone.Router
routes:
".*": "main"
main: ->
@titleView ||= new AppName.TitleView el: $('#app')[0]
@titleView.render()
但是,为了我,我无法从Backbone Events绑定到#search
。我的破解(在代码中)只是通过initialize
函数中的jQuery进行绑定。
任何想法是怎么回事?我希望这是一个简单的错字或错误的初始化。
你,先生,是CoffeeScript的堆栈溢出问题的蝙蝠侠!谢谢! – CamelBlues 2013-03-24 20:55:30