代码之家  ›  专栏  ›  技术社区  ›  bitsprint

在jQuery回调中访问父属性

  •  2
  • bitsprint  · 技术社区  · 17 年前

    不确定我的措辞是否正确,但在回调中如何引用基类的controls属性?

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

    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();
                });
            }
        }
    };
    

    非常感谢,

    保罗

    3 回复  |  直到 17 年前
        1
  •  2
  •   Damir Zekić    17 年前

    使用闭包的功能:

    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
  •  2
  •   Community Mohan Dere    9 年前

    虽然 closures preferred ,也可以使用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();
                });
            }
        }
    };
    
        3
  •  1
  •   Peter Bailey    17 年前

    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));
        }
    }
    

    };