The binding class method to event of html object in JQuery

Did you try to bind method of javascript class to event of html object?
That’s not so simple as it may imagine at first sign.

I almost ensure that you’ll try to write something like this first:

<script src="jquery.js"></script>
 
<button id="test_button">Say Hello</button>
 
<script type="text/javascript">
	function MyClass(){
		this.inner_variable = "Hello world";
		this.foo = function(){
			alert(this.inner_variable);
		}
		$("#test_button").click(this.foo);
	}
	var obj = new MyClass();
</script>

But js interpreter will think that you bind just function without object. It’s just equivalent of this code:

	function foo(){
		alert(this.inner_variable);
	}
	$("#test_button").click(foo);

So of course the both scripts show `undefined`, because there is no `inner_variable` in both variables’ scopes.

I found decision but I’m not sure that it’s the best solution:

	function MyClass(){
		this.inner_variable = "Hello world";
		this.foo = function(){
			alert(this.inner_variable);
		}
		$("#test_button").data("obj", this).click(function(e){
			$(this).data("obj").foo()
		});
	}
	var obj = new MyClass();

Of course you are welcome to suggest the improving this code if you want – just comment it..

Books to read

Leave a Reply

Your email address will not be published. Required fields are marked *