【问题标题】:Access jQuery object inside a function bound to another object在绑定到另一个对象的函数内访问 jQuery 对象
【发布时间】:2014-02-18 12:13:43
【问题描述】:
var obj = {
    someFunction : function() {
        $('#someID').on('change', '#someOtherId', function(e) {
            this.someOtherFunction(); // works fine
        }.bind(this));
    },

    someOtherFunction : function() {
        // do something
    }
}

上面的代码工作正常,但我不确定如何在someFunction 中使用$(this) 访问jQuery 包装的元素。感谢您的帮助。

【问题讨论】:

  • 要么使用$(e.target),要么不使用bind
  • 使用$(e.currentTarget)
  • e.target 是跨浏览器吗?
  • 是的,由于 jQuery 对事件对象进行了规范化,您可以使用 W3C 标准中的所有对象。但是,如果您的代码需要跨浏览器,请确保您 polyfill bind,因为

标签: javascript jquery oop object bind


【解决方案1】:
var obj = {
    someFunction : function() {
        var me = this;
        $('#someID').on('change', '#someOtherId', function(e) {
            var $elem = $(this); // element / jquery object
            me.someOtherFunction(); // works fine
            // me is assigned in "obj" scope 
        });
    },

    someOtherFunction : function() {
        // do something
    }
}

【讨论】:

  • 这真的是处理这种情况的有效方法吗?
  • 是的。像 ExtJS 这样的大型库也在使用这种方法。
  • 如果他只想要回调函数? :\
  • 抱歉误会:\取消了。
【解决方案2】:

我认为干净的方法是使用$.proxy

var obj = {
    someFunction : function() {
        $('#someID').on('change', '#someOtherId', $.proxy(this.someOtherFunction, this));
    },

    someOtherFunction : function(e) {
        //this is the jquery $(this) element
        var $el = $(e.currentTarget);

        //the "this" is the main "obj" object
    }
}

关于匿名回调函数:

    var obj = {
        someFunction : function() {
            $('#someID').on('change', '#someOtherId', $.proxy(function (e) {
                //this is the jquery $(this) element
                var $el = $(e.currentTarget);

                //the "this" is the main "obj" object
                this.someOtherFunction();
            }, this));
        },

        someOtherFunction : function(e) {

        }
    }

【讨论】:

  • 两者..在不同的部分,根据要求。
  • 是的,你的答案非常好,但@sjkm 的答案可以在任何地方使用,而不仅仅是用于回调。我尝试在回调函数(闭包)中使用你的答案,但它不起作用。
  • 见上文...不要忘记 (e) 变量。我认为我的两种方式都更好。我不是为了你改变“正确”而是为了你学习...... :)
猜你喜欢
  • 2013-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多