2011-10-12 40 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)) 
} 
相關問題