2011-10-12 84 views
18

我在一个javascript对象(vr roxx :))里面,但是每次我用jQuery做一个事件绑定时,我必须通过data参数包含主对象实例的上下文才能使用它。在jQuery中没有简单/简洁的方法吗?有没有办法传递上下文来绑定jQuery?

var oink = 
{ 
    pig: null, 

    options:  
    { 
     showPigMom: 0 
    }, 

    init: function(pigObj) 
    { 

     //Show the pigmom 
     $(this.doc).bind('keyup click', {o: this}, function(e) 
     { 
      var o = e.data.o; 
      if (o.options.showpath) 
       o.doWhatever(); 
     }); 

    ... 
+8

...在这个对象他有一个猪:O,e.data.o .... – Blazemonger

回答

23

我用的是$.proxy()功能

init: function(pigObj) 
{ 
    //Show the pigmom 
    $(this.doc).bind('keyup click', $.proxy(function(e) { 
     if (this.options.showpath) 
      this.doWhatever(); 
     $(e.currentTarget).text(); // use this to access the clicked element 
    }, this)); 
} 
3
init: function() { 
    var self = this; 
    $(this.doc).bind('keyup click', function() { 
     if (self.options.showpath) self.doWhatever(); 
    }); 
} 
+1

$。代理()或_.bind()应该优先于具有明确上下文变量的旧学校 – mPrinC

+1

'proxy'看起来更清洁,但旧学校@mPrinC有什么问题? – seebiscuit

2
init: function() { 
    $(this.doc).bind('keyup click', function() { 
     if (this.options.showpath) this.doWhatever(); 
     $(e.currentTarget).text(); // use this to access the clicked element 
    }.bind(this)) 
} 
相关问题