开发者

How to add dynamic events for view?

开发者 https://www.devze.com 2023-03-16 07:02 出处:网络
How can I add dynamic events in my view class in Backbone.js I have a View Class with var myViewC开发者_开发问答lass = Backbone.View.extend({

How can I add dynamic events in my view class in Backbone.js

I have a View Class with

var myViewC开发者_开发问答lass = Backbone.View.extend({
    events: {
        'change select': 'changeSelect',
        'click a.changeLink': 'clearSelect'
    },

    initialize: function() {
        this.delegateEvents({'click select': 'changeSelect'});
    },

    .
    .
    .        
});

This is adding {'click select': 'changeSelect'} event, however somehow {'click a.changeLink': 'clearSelect'} doesn't woek.

anybody knows the solution?

Thanks, Rohan


Backbone automatically delegates events from the events attribute of your view. You are overrriding the previously delegated events. You can call $(this.el).delegate(...) but you can also do

this.delegateEvents(_.extend(this.events, {'click select': 'changeSelect'}));


Since I'm doing this a lot, here is my tiny Backbone extension (based on Julien's answer and my testing):

Backbone.View.prototype.addEvents = function(events) {
  this.delegateEvents( _.extend(_.clone(this.events), events) );
};

Use:

BaseResizable.View = Base.View.extend({
  initialize: function() {
    Base.View.prototype.initialize.call(this);
    this.addEvents({
      'resizestop': 'resizeStop'
    });
  },
  resizeStop: function(event, ui){...}
}

You will have to do addEvents() again if you use undelegateEvents().

0

精彩评论

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

关注公众号