开发者

Backbone jQuery can only trigger events on elements in Template?

开发者 https://www.devze.com 2023-03-30 22:12 出处:网络
I am trying to use the following to trigger functions when a mouse clicked is detected several a buttons on the page

I am trying to use the following to trigger functions when a mouse clicked is detected several a buttons on the page

    var view=Backbone.View.Extend({
     template:_.template($("tem").html()),
     events: {
          "click button" : "foo"
      },
     })

Then I placed button inside the template script, and outside of the template, where it i开发者_开发百科s simply directly generated HTML.

However, it only registers the click on the button in the template, but not the direct HTML button.

How to solve this?


Probably the easiest thing to do would be to set up custom binding in your initialize function in the view, like this:

 var view = Backbone.View.Extend({
      template:_.template($("tem").html()),
      events: {
           "click button" : "foo"
      },
      initialize: function() {
           _.bindAll(this, 'foo'); //so foo's "this" is the view
           $('selector to direct HTML button').delegate('click', this.foo); //so when the out-of-template button is clicked, the foo handler is called
      }
 })


You need to properly specify the el in your view. Which I didn't. Because the events{} calls jQuery delegate function. And delegate is bound to that as the root element

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号