将主干事件映射到单独的主干类文件中
我将 CoffeeScript 与 Backbone 视图类一起使用。当我将类包含在与 html 相同的页面中时,一切正常。当我使用单独的文件并导出该类时,它会初始化,但事件不会映射。
类文件是:
root = exports ? this
class root.AppView extends Backbone.View
el: $("#app")
events:
'click #appBtn1' : 'handleEvent'
'click #appBtn2' : 'handleEvent'
initialize: =>
alert 'init'
handleEvent: =>
alert 'event'
仅触发初始化函数。当代码位于单独的类中时,我需要更改什么来映射事件?
I'm using CoffeeScript with a Backbone view class. When I include the class in the same page as the html everything works fine. When I use a separate file and export the class, it initialises but the events aren't mapped.
The class file is:
root = exports ? this
class root.AppView extends Backbone.View
el: $("#app")
events:
'click #appBtn1' : 'handleEvent'
'click #appBtn2' : 'handleEvent'
initialize: =>
alert 'init'
handleEvent: =>
alert 'event'
Only the initialize function fires. What do I need to alter to map the events when the code is in a separate class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,
当您定义类时,该函数会立即运行。因此,当类位于单独的文件中时,
#app
元素尚未(不一定)存在于 DOM 中。您应该做的是使用选择器字符串,当类实例化时,Backbone 会将其传递给
$
函数:The problem is that the function
runs immediately when you define the class. So when the class is in a separate file, the
#app
element doesn't (necessarily) exist in the DOM yet.What you should be doing is using a selector string instead, which Backbone will pass to the
$
function when the class is instantiated: