尝试通过传入函数绑定回调会引发错误

Bra*_*don 5 javascript jquery events backbone.js jquery-1.7

我只想在输入使用jQuery 1.7.2和Backbone.js更改值时触发事件.

目前我有以下(有效)

MyView: Backbone.View.extend({
  initialize: function() {

    this.colorInput = $("<input />", {
         "id": "color",
         "name": "color",
         "value": this.model.get("color")
    });

    var self = this;
    this.colorInput.on("change", function() {
      self.changeColor();
    });

  },
  changeColor: function() {
    var color = this.colorInput.val();
    this.model.set("color", color);
  }
});
Run Code Online (Sandbox Code Playgroud)

我正试图通过我的功能传递另一种方式.

this.colorInput.on("change", this.changeColor, this);
Run Code Online (Sandbox Code Playgroud)

但是当试图这样做时,它会抛出错误

((jQuery.event.special [handleObj.origType] || {}).handle || handleObj.handler).apply不是函数
.apply(matched.elem,args);

(第3332行)

我无法弄明白.任何想法为什么这种方式不起作用?

mu *_*ort 11

你是混淆jQuery的on:

.on(events [,selector] [,data],handler(eventObject)).
on(events-map [,selector] [,data])

Backbone的on:

object.on(event,callback,[context])

Backbone将上下文作为第三个参数,jQuery没有.看起来jQuery on正在将您的第三个参数解释为handler(eventObject)并试图将其称为函数,这将解释您所看到的错误消息.

通常你会这样做:

MyView: Backbone.View.extend({
  events: {
    'change input': 'changeColor'
  },
  initialize: function() {
    this.colorInput = $("<input />", {
       "id": "color",
       "name": "color",
       "value": this.model.get("color")
    });
  },
  render: function() {
    this.$el.append(this.colorInput);
    return this;
  },
  changeColor: function() {
    var color = this.colorInput.val();
    this.model.set("color", color);
  }
});
Run Code Online (Sandbox Code Playgroud)

让Backbone的事件委托系统处理好事情.