结合在骨干视图的多个事件类型(Binding multiple event types in bac

2019-07-29 15:44发布

我在想,如果有可能,一条线路中的绑定骨干多个事件类型。

考虑以下:

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

基本上,我想知道是,如果有可能的情况下为“点击”和“touchstart”成一条线组合结合 - 沿着线:

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

任何建议,将不胜感激。

Answer 1:

它的观点jQuery的事件,这是通过约束是不可能delegateEvents 。 它是可能的骨干事件 ,虽然:

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


Answer 2:

任何有兴趣,我结束了覆盖delegateEvents在Backbone.View。

只有少数修改的线来获得所需的功能。

你可以在我看到一个差异在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);
            }
        });
    }
}


Answer 3:

我们也可以做到这一点,如下。 随着优势来管理每个事件之间的空间。

Github上提交这里

它添加在骨干直接:

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'
}


文章来源: Binding multiple event types in backbone views