代码之家  ›  专栏  ›  技术社区  ›  John Topley

javascript“this”在事件处理程序中引用了错误的对象

  •  2
  • John Topley  · 技术社区  · 15 年前

    我正在使用原型编写一些MVC JavaScript代码。问题是当我提到 this 在下面的代码片段中,它当然引用了窗口对象,而我需要它引用我的控制器实例,以便它可以调用 updateValue 函数,传递HTML元素ID。

    我想我得用 bind bindAsEventListener 但我真的不明白怎么做。

    var Foo = {
      Controller: Class.create({
        observeEvents: function() {
          $$("#myform input").each(function(input) {
            input.observe("blur", this.updateValue(input.id); // <- wrong this!
          });
        },
    
        updateValue: function(elementID) {
          ...
        }
      })
    }
    

    任何帮助都将不胜感激。

    1 回复  |  直到 13 年前
        1
  •  2
  •   Jason Orendorff Oliver    15 年前

    这应该有效。

        observeEvents: function() {
          var Controller = this;
          $$("#myform input").each(function(input) {
            input.observe("blur", Controller.updateValue.bind(Controller, input.id));
          });
         ...
    

    如果你不想学习如何使用 bind (坦率地说,我不怪你)然后你可以忘记它,用另一个十几岁的结束语。

        observeEvents: function() {
          var Controller = this;
          $$("#myform input").each(function(input) {
            input.observe("blur", function(event) {
                                    Controller.updateValue(input.id);
                                  });
          });
         ...