views:

33

answers:

2

I want to use values of the calling object within the jquery code block, but 'this' is mapped to the jquery object and not eh caller! How to solve this PLEASE?

// class
myClass = function (){
    // member object
    this._localVars = {
        _elementClass:'.elem-class',
        _dots:null,
        _dotStatus:null
    };

    // member function
    this.func1 = function() {
        $(this._elementClass).each(function(_index, _element){
            // this._localVars._dots[_index] = _element; ... this line throws an error 'this._localVars' is undefined ... as 'this' is html element here and not an object of the calling class
        });
    };
};

Please suggest how can I use the 'this' inside the jquery code block to refer the variables/objects of the class and not HTML/jQuery.

Thanks

+2  A: 

Try saving this object into a local variable

    var myObject = this;
    $(this._elementClass).each(function(_index, _element){
        myObject._localVars._dots[_index] = _element;
    });
Nikita Rybak
I will give that a shot, however if I go with 'var myObject = this;' won't it create a local copy of the object and then whatever manipulation I do, will effect that local copy and not the global collection?
Mandeep
@Mandeep No, it will just create a reference to the old object. It's not C.
Nikita Rybak
A: 

You can use the jQuery.proxy method to set the value of this that you want.

You pass your function as the first parameter, and the current this as the second.

myClass = function (){
    this._localVars = {
        _elementClass:'.elem-class',
        _dots:[],
        _dotStatus:null
    };
    this.func1 = function() {
        $(this._localVars._elementClass).each( $.proxy(function(_index, _element) {
             this._localVars._dots[_index] = _element;
        }, this));
    };
};

var cl = new myClass();

cl.func1();

console.log(cl._localVars._dots);
patrick dw
thank a ton bro ... this is exactly what i was looking for. thank you!
Mandeep
@Mandeep - You're welcome. :o)
patrick dw