0

在骨干网我想扩展 Backbone.View.prototype.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('Event "' + events[key] + '" does not exist');
        var match = key.match(eventSplitter);
        var eventName = match[1], selector = match[2];
        method = _.bind(method, this);
        eventName += '.delegateEvents' + this.cid;
        if (selector === '') {
          this.$el.bind(eventName, method);
        } else {
          this.$el.delegate(selector, eventName, method);
        }
      }
    }

在其中添加一个附加功能。这是一种在不完全覆盖原型的情况下扩展原型的方法吗?

就我而言,我正在尝试访问eventsarg。

编辑:我试图实现一些类似的东西

function (events) {
          if (events['rightclick .element']){ App.doStuff() }

          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('Event "' + events[key] + '" does not exist');
            var match = key.match(eventSplitter);
            var eventName = match[1], selector = match[2];
            method = _.bind(method, this);
            eventName += '.delegateEvents' + this.cid;
            if (selector === '') {
              this.$el.bind(eventName, method);
            } else {
              this.$el.delegate(selector, eventName, method);
            }
          }
        }
4

1 回答 1

1

如果你一开始只是想要一些东西,那么你可以这样做:

var delegateEvents = Backbone.View.prototype.delegateEvents;
Backbone.View.prototype.delegateEvents = function(events) {
    // You have to do this here because delegateEvents rarely
    // gets the events from its argument, they almost always
    // come from this.events.
    if(!(events || (events = _(this).result('events'))))
        return;

    // Now do your special stuff.
    if(events['rightclick .element'])
        App.doStuff();

    // And chain it off to the original implementation. We'll
    // always supply the events argument here since we've already
    // done the "is it passed or in this?" logic up above.
    delegateEvents.call(this, events);
};

请注意,_.result它的作用与旧getValue内部函数的作用相同。

演示:http: //jsfiddle.net/ambiguous/25Xh9/

此外,rightclick我不知道任何事件,但如果需要,有办法检测到事件。

于 2013-10-20T23:09:39.823 回答