2010-07-07 5 views
1

Voir ce code:rappel jQuery dans l'objet parent non jQuery

var MyObject = new function() { 

    this.tos = new Array(); 

    this.show = function() { 
    this.clearTimeouts(); 
    $("#divExample").slideDown(null,function() { 
     MyObject.tos[MyObject.tos.length] = 
     setTimeout(function(){MyObject.doSomething();} , 1800); 
    }); 
    return; 
    }; 

    this.doSomething = function() { 
    return; 
    }; 

    this.clearTimeouts = function(){ 
    for (var i=0; i<this.tos.length; i++) 
     clearTimeout(this.tos[i]); 
    this.tos = new Array(); 
    return; 
    }; 

} 

MyObject et il est méthodes sont utilisées dans quelques endroits. Peut-être que c'est une mauvaise façon de le faire, je ne sais pas. Je ne voulais pas l'attacher trop étroitement avec jQuery pour mes propres raisons, donc le laisser comme ceci avait du sens car je peux facilement changer la diapositive en style.display. Le problème est que je n'aime pas référencer l'objet comme MyObject dans le rappel de la diapositive jQuery, mais je dois ajouter la référence timeout à mon tableau de sorte qu'ils puissent tous être effacés. Y a-t-il une meilleure manière de faire cela?

Merci!

Répondre

4

Vous pouvez essayer quelque chose comme ceci:

this.show = function() { 
    var obj = this; 
    obj.clearTimeouts(); 
    $("#divExample").slideDown(null,function() { 
     obj.tos[obj.tos.length] = 
     setTimeout(function(){obj.doSomething();} , 1800); 
    }); 
    return; 
    }; 
+0

Cela a bien fonctionné. Merci beaucoup! – Erick

1
var MyObject = (function() { 

    // private variable 
    tos = new Array(); 

    // private method 
    function doSomething() { 
     // do something 
     // .. 
    }  

    // return an instance with public methods 
    return { 
    show: function() { 
     this.clearTimeouts(); 
     $("#divExample").slideDown(null,function() { 
     tos[tos.length] = 
      setTimeout(function(){ doSomething(); } , 1800); 
     }); 
    }, 
    clearTimeouts: function() { 
     for (var i=0; i<tos.length; i++) 
     clearTimeout(tos[i]); 
     tos = new Array(); 
    } 
    } 
}​;​