Backbone.js Can';似乎无法在Coffeescript中正确绑定主干事件
好的,所以我很难让事件绑定与Coffeescript和主干一起工作。我有一种感觉,这与我如何初始化一切有关;我觉得活动代表团甚至都没有运行 以下是我的查看代码:Backbone.js Can';似乎无法在Coffeescript中正确绑定主干事件,backbone.js,coffeescript,backbone-events,event-binding,Backbone.js,Coffeescript,Backbone Events,Event Binding,好的,所以我很难让事件绑定与Coffeescript和主干一起工作。我有一种感觉,这与我如何初始化一切有关;我觉得活动代表团甚至都没有运行 以下是我的查看代码: $ -> class AppName.TitleView extends Backbone.View template: JST['templates/title'] collection: new AppName.Members events: "keypress #search"
$ ->
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
启动):
但就我个人而言,我无法从主干事件绑定到#search
。我的hack(在代码中)只是通过initialize
函数中的jQuery进行绑定
知道发生了什么吗?我希望这是一个简单的输入错误或错误的初始化。视图事件使用jQuery的委托形式绑定到视图的
el
。这意味着您在视图的事件
对象中提到的所有内容必须位于视图的el
内,否则不会触发事件处理程序
默认情况下,视图是空的
,视图将在需要时创建该
,并将事件绑定到该
。您可能会注意到,您没有在代码中的任何位置使用this.el
或this.el
;您的事件被正确绑定,但它们被绑定到您放入DOM中的任何内容,因此看起来这些事件不起作用
出现两种直接的可能性:
#app
作为视图的el
:
class AppName.TitleView extends Backbone.View
#...
el: '#app'
#...
render: =>
@$el.html(@template)
@
el
,仅用于查看:
class AppName.TitleView extends Backbone.View
#...
render: =>
@$el.html(@template)
@
v = new AppName.TitleView
$('#app').append(v.render().el)
@template
几乎总是一个函数,因此您想说:
$('#app').html(@template())
先生,你是咖啡的蝙蝠侠!非常感谢。
$('#app').html(@template())