为什么不会'骨干火我的活动?

发布于 2024-12-27 17:53:23 字数 397 浏览 3 评论 0原文

我的类定义如下:

class NewUser extends Backbone.View
  template : JST["backbone/templates/events/new"]
  events : 
    'click button' : 'hello'
  hello : ->
    alert('hi')
  render : ->
    @el = $(@template())
    @ 

我按如下方式初始化页面:

$('body').append(new NewUser().render().el)

然而,当我单击按钮时,没有显示任何警报。有人看到我的代码有什么问题吗?视图呈现,但事件从未注册。

My class is defined as below:

class NewUser extends Backbone.View
  template : JST["backbone/templates/events/new"]
  events : 
    'click button' : 'hello'
  hello : ->
    alert('hi')
  render : ->
    @el = $(@template())
    @ 

I initialize the page as follows:

$('body').append(new NewUser().render().el)

Yet when I click the button, no alert displays. Does anyone see anything wrong with my code? The view renders, but the events never register.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傻比既视感 2025-01-03 17:53:23

您正在 render 方法中创建 @el

render : ->
    @el = $(@template())
    @ 

但您忽略了调用 delegateEvents

使用 jQuery 的 delegate 函数为视图中的 DOM 事件提供声明性回调。 [...] 默认情况下,delegateEvents 会在 View 的构造函数中为您调用 [...]

因此,您的事件永远不会绑定到您添加的 @el到 DOM 并且你的按钮没有任何用处。您的渲染应如下所示:

render : ->
    @el = $(@template())
    @delegateEvents()
    @

You're creating your @el in your render method:

render : ->
    @el = $(@template())
    @ 

but you neglect to call delegateEvents:

Uses jQuery's delegate function to provide declarative callbacks for DOM events within a view. [...] By default, delegateEvents is called within the View's constructor for you [...]

So, your events never get bound to the @el that you add to the DOM and your button does nothing useful. Your render should look like this:

render : ->
    @el = $(@template())
    @delegateEvents()
    @
南冥有猫 2025-01-03 17:53:23

按钮是渲染到视图的 el 的模板的一部分吗?

如果不是,则不会触发 hello 事件,因为事件哈希仅限于视图本身内的事件。在这种情况下,您需要手动绑定到 render 方法中的事件

render : ->
  @el = $(@template());
  $('#buttonId').click(@hello);

Is the button part of the template which is rendered to the view's el?

If it's not then the hello event won't be fired because the events hash is limited to events within the view itself. You will need to manually bind to the event in the render method in that case

render : ->
  @el = $(@template());
  $('#buttonId').click(@hello);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文