2014-01-27 183 views
0
var obj = { 
    someFunction : function() { 
     $('#someID').on('change', '#someOtherId', function(e) { 
      this.someOtherFunction(); // works fine 
     }.bind(this)); 
    }, 

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

上面这段代码在函数内部访问jQuery对象工作正常,但我不知道如何访问jQuery的包裹使用$(this)someFunction内部元素。帮助表示赞赏。绑定到另一个对象

+0

要么使用'$(e.target)'或不使用绑定 – sroes

+0

使用'$(e.currentTarget)' –

+0

是e.target跨浏览器吗? –

回答

4
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 
    } 
} 
+0

这是否真的是一种处理此类情况的有效方法? –

+0

是的。像ExtJS这样的巨大图书馆也在使用这种方法。 – sjkm

+0

如果他只需要回调函数? :\ – justtal

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) { 

     } 
    } 
+0

我希望我能标记两个答案正确! –

+0

你在你的代码中实现了哪一个? :) – justtal

+0

都在不同的部分,根据要求。 –

相关问题