【问题标题】:Access parent property in jQuery callback在 jQuery 回调中访问父属性
【发布时间】:2010-09-20 05:33:48
【问题描述】:

不确定我的表述是否正确,但在回调中如何引用基类的控件属性?

这一直困扰着我一段时间,我通常会解决它,但如果有人能指导我如何正确地做到这一点,我将不胜感激。

var base = function() {
    var controls = {};

    return {
        init: function(c) {
            this.controls = c
        },
        foo: function(args) {
            this.init(args.controls);
            $(this.controls.DropDown).change(function() {
                $(this.controls.PlaceHolder).toggle();
            });
        }
    }
};

非常感谢,

保罗

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    使用闭包的力量:

    var base = function() {
        var controls = {};
    
        return {
            init: function(c) {
                    this.controls = c
            },
            foo: function(args) {
                    var self = this;
    
                    this.init(args.controls);
                    $(this.controls.DropDown).change(function() {
                            $(self.controls.PlaceHolder).toggle();
                    });
            }
        }
    };
    

    【讨论】:

      【解决方案2】:

      虽然closurespreferred,你也可以使用jquery bind 来传递一个对象:

      var base = function() {
          var controls = {};
      
          return {
              init: function(c) {
                  this.controls = c
              },
              foo: function(args) {
                  this.init(args.controls);
                  $(this.controls.DropDown).bind('change', {controls: this.controls}, function(event) {
                      $(event.data.controls.PlaceHolder).toggle();
                  });
              }
          }
      };
      

      【讨论】:

      • 我喜欢这种方法,我想如果我在我的代码中广泛使用 jQuery,我应该使用 bind 方法。我可能只使用闭包一段时间,以便习惯使用它,然后一旦熟悉我就可以使用任何一个。谢谢。
      【解决方案3】:

      您需要在这里利用闭包。

      var base = function() {
      var controls = {};
      
      return {
          init: function(c) {
                  this.controls = c
          },
          foo: function(args) {
                  this.init(args.controls);
                  $(this.controls.DropDown).change(function(controls) {
                          return function(){
                              $(controls.PlaceHolder).toggle();
                          }
                  }(this.controls));
          }
      }
      

      };

      【讨论】:

      • 用更优雅的解决方案打败我:D
      • 当我使用这种方法时,似乎发生了一些奇怪的事情。点击事件在页面加载时触发。我认为这与回调函数中的 controls 参数有关,因为当我删除 click 事件时不会自动触发。
      猜你喜欢
      • 2010-10-05
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      相关资源
      最近更新 更多