为什么我的视图事件没有触发?

发布于 2025-01-04 04:32:49 字数 408 浏览 2 评论 0原文

这是我的 CoffeeScript 代码:

$(document).ready ->
  SearchView = Backbone.View.extend
    tagName: "form"
    className: "search"
    events: {
      "click label":"search"
    }
    search: ->
      console.log("HERE")

  searchView = new SearchView()

这是我的 HTML:

%form#search.search
  %label
    Search
  %input

但单击表单不会触发任何事件。有什么想法吗?

Here's my CoffeeScript code:

$(document).ready ->
  SearchView = Backbone.View.extend
    tagName: "form"
    className: "search"
    events: {
      "click label":"search"
    }
    search: ->
      console.log("HERE")

  searchView = new SearchView()

And here's my HTML:

%form#search.search
  %label
    Search
  %input

But clicking the form is not triggering any events. Any ideas why?

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

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

发布评论

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

评论(1

城歌 2025-01-11 04:32:49

您误解了 tagNameclassName 的工作原理。当您设置这些时:

tagName: "form"
className: "search"

这仅意味着您将拥有

如果您想使用 tagNameclassName 那么您将需要 render 来充实您的表单:

render: ->
    $(@el).append('<label>Search</label><input>')
    @

然后您将调用 render 并将 el 添加到 DOM,如下所示:

searchView = new SearchView()
$('div').append(searchView.render().el) # 'div' is just an example of course

演示:http://jsfiddle.net/ambigously/ubqqE/

如果你想绑定到现有的 HTML,那么你可以使用 el 而不是 tagName 和 className 像这样:

SearchView = Backbone.View.extend
    el: '#search'
    #...

演示:http://jsfiddle.net/ambiguously/FfDg6/

You misunderstand how tagName and className work. When you set these:

tagName: "form"
className: "search"

That just means that you'll have <form class=​"search">​</form>​ in @el. Those settings don't bind your view to what the form.search selector matches and you never add @el to the DOM so your events don't end up bound to anything at all.

If you want to use tagName and className then you'll want a render to flesh out your form:

render: ->
    $(@el).append('<label>Search</label><input>')
    @

And then you'd call render and add el to the DOM with something like this:

searchView = new SearchView()
$('div').append(searchView.render().el) # 'div' is just an example of course

Demo: http://jsfiddle.net/ambiguous/ubqqE/

If you wanted to bind to existing HTML then you could use el instead of tagName and className like this:

SearchView = Backbone.View.extend
    el: '#search'
    #...

Demo: http://jsfiddle.net/ambiguous/FfDg6/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文