在骨干视图中绑定多个事件类型

时间:2012-05-30 06:33:17

标签: javascript backbone.js backbone-events backbone-views

我想知道是否有可能在一条线路中绑定骨干网中的多个事件类型。

请考虑以下事项:

var MyView = Backbone.View.extend({
    id: 'foo',
    events: {
        'click .bar': 'doSomething',
        'touchstart .bar': 'doSomething'
    },
    doSomething: function(e) {
        console.log(e.type);
    }
});

基本上我想知道的是,是否可以将'click'和'touchstart'的事件绑定组合成一行 - 沿着以下几行:

events: { 'click,touchstart .bar': 'doSomething' }

任何建议都将不胜感激。

3 个答案:

答案 0 :(得分:18)

视图jQuery事件是不可能的,它们通过delegateEvents绑定。不过它是possible for backbone events

book.on("change:title change:author", ...);

答案 1 :(得分:15)

对于任何感兴趣的人,我最终在Backbone.View中覆盖了delegateEvents

只有少数修改过的行才能获得所需的功能。

您可以在commit on github

中看到差异

以下是delegateEvents处于修改状态:

delegateEvents: function(events) {
    if (!(events || (events = getValue(this, 'events')))) return;
    this.undelegateEvents();
    for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[events[key]];
        if (!method) throw new Error('Method "' + events[key] + '" does not exist');
        var match = key.match(delegateEventSplitter);
        var eventTypes = match[1].split(','), selector = match[2];
        method = _.bind(method, this);
        var self = this;
        _(eventTypes).each(function(eventName) {
            eventName += '.delegateEvents' + self.cid;
            if (selector === '') {
              self.$el.bind(eventName, method);
            } else {
                self.$el.delegate(selector, eventName, method);
            }
        });
    }
}

答案 2 :(得分:1)

我们也可以这样做。 具有管理每个事件之间空间的优势。

Github commit here

直接在Backbone中添加它:

delegateEvents: function(events) {
  events || (events = _.result(this, 'events'));
  if (!events) return this;
  this.undelegateEvents();
  for (var key in events) {
    var method = events[key];
    if (!_.isFunction(method)) method = this[method];
    if (!method) continue;
    var match = key.match(delegateEventSplitter);
    this.delegate(match[1], match[2], _.bind(method, this));
  }
  return this;
}

覆盖delegateEvents方法:

Backbone.View.prototype.originalDelegateEvents = Backbone.View.prototype.delegateEvents;
Backbone.View.prototype.delegateEvents = function(events) {
    events || (events = _.result(this, 'events'));
    if (!events) return this;
    this.undelegateEvents();
    for (var key in events) {
        var method = events[key], combinedEvents = key.split(',');
        if (!_.isFunction(method)) method = this[method];
        if (!method) continue;

        for(var i = 0, match = null; i < combinedEvents.length; ++i) {
            match = combinedEvents[i].trim().match(/^(\S+)\s*(.*)$/);
            this.delegate(match[1], match[2], _.bind(method, this));
        }
    }
    return this;
};

我们现在可以在一行中管理事件:

events: { 
    'click a[data-anchor], wheel, keydown': 'scroll'
}