javascript - network - backbone意思




在骨幹視圖中綁定多個事件類型 (2)

對於任何感興趣的人,我最終在Backbone.View中覆蓋了delegateEvents

只有少數修改的行可以獲得所需的功能。

您可以在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);
            }
        });
    }
}

我想知道是否有可能在一條線路中綁定主幹中的多個事件類型。

考慮以下:

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

任何建議,將不勝感激。


我們也可以這樣做。 具有管理每個事件之間空間的優勢。

Github在這裡提交

直接在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'
}






backbone-views