jqueryjavascript-namespaces

How assign value to a namespace object variable if it is get it inside a jquery on click definition


I want to know how can I save a value inside a jquery bind when this is inside a namespace.

var obj = obj || (obj ={ 
    valuetosave:-1,
    init:function(){
        $("some selector").on("click",function(){
            tmpval = I get some value here
            how can asign 'tmpval' to obj.valuetosave if I can't use this because 
            is in the jquery scope
        })
    }
})

I know that neither the title or my little description is not much useful, I hope the little example can speak about my issue.

Thanks


Solution

  • If you want to refer to the current instance of obj then u should use this keyword. for example

    var obj = obj || ({ 
      valuetosave:-1,
      init:function(){
    
        var self = this;  // preserver your global instance in a variable
          $("#mybutton").on("click",function(){               
              var tmpval = 'I get some value here'
              // here `this` refers to  the function event instance , not obj instance
              // So i am using self (which is global instance variable)
              self.valuetosave = tmpval;
              alert(self.valuetosave);
          });
      }
    });
    

    Let me know if u need more help, checkout jsfiddle link.