2011-10-12 12 views
18

Sono all'interno di un oggetto javascript (vr roxx :)), ma ogni volta che faccio un evento legato a jQuery devo includere il contesto dell'istanza dell'oggetto principale attraverso il parametro data per lavorare con esso. Non c'è un modo facile/pulito per farlo in jQuery?C'è un modo per passare il contesto per legare in 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

... e in questo oggetto aveva un maiale: o, e.data.o .... – Blazemonger

risposta

23

a utilizzare la funzione $.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

$. proxy() o _.bind() dovrebbero essere preferiti alla vecchia scuola con variabili di contesto esplicite – mPrinC

+1

'proxy' sembra più pulito, ma cosa c'è di sbagliato nella vecchia scuola, @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)) 
} 
Problemi correlati