Jquery binding woes -


i've read number of explanations seems can't grasp concept of binding. in following code how make 'this' refer object rather element called 'search' function?

<!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <meta charset=utf-8 > <title></title> </head> <body> <input id="inpt"> <script> obj = {   theelement: null,   func1: function(inpt) {     this.theelement = $(inpt);     this.theelement.keyup(this.search);   },   search: function(e) {     alert(this);  //'this' refers input element (#inpt) want refer 'obj'   } }; obj.func1('#inpt'); </script> </body> </html> 

hope makes sense...

two ways:

1. use own closure:

obj = {   theelement: null,   func1: function(inpt) {     var self = this;     this.theelement = $(inpt);     this.theelement.keyup(function() {         self.search();     });   },   search: function(e) {     alert(this);  //'this' refers input element (#inpt) want refer 'obj'   } }; 

more reading: closures not complicated

edit: although patrick points out, have reference in obj , technically don't need self. above more of general solution (particularly when use factory functions rather singleton objects).

2. use 1 jquery creates you:

...via jquery.proxy:

obj = {   theelement: null,   func1: function(inpt) {     this.theelement = $(inpt);     this.theelement.keyup(jquery.proxy(this.search, this));   },   search: function(e) {     alert(this);  //'this' refers input element (#inpt) want refer 'obj'   } }; 

more reading: you must remember this


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -