2011-10-12 32 views
18

Estoy dentro de un objeto javascript (vr roxx :)), pero cada vez que hago un evento se une con jQuery tengo que incluir el contexto de la instancia del objeto principal a través del parámetro de datos para poder trabajar con él. ¿No hay una manera fácil/clara de hacer esto en jQuery?¿Hay alguna forma de pasar el contexto para vincular 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

... y en este objeto tenía un cerdo: o, e.data.o .... – Blazemonger

Respuesta

23

utilizo la función $.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() deberían preferirse a la antigua escuela con variables de contexto explícitas – mPrinC

+1

'proxy' se ve más limpio, pero ¿qué hay de malo en la vieja escuela, @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)) 
} 
Cuestiones relacionadas