Binding Events to Objects Using a Closure
What's the best practice for binding events to Javascript objects using jQuery? The following code works, but I'm using my own function to create a closure, and I've found that this doesn't always work with more complicated uses of jQuery. Is there a better way?
-
<html>
<head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
function closure(obj, funcName){
return function(){
return obj[funcName].apply(obj, arguments)
};
}
function MyObject(){
this.name = 'Bob';
this.someMethod = function(e){
alert('there was a '+e.type+' on '+this.name)
}
}
obj = new MyObject();
jQuery(document).ready(function(){
//jQuery('#main').bind('click', obj.someMethod); // Does not work.
jQuery('#main').bind('click', closure(obj, 'someMethod'));
});
</script>
</head>
<body>
<div id="main">click here to see Bob</div>
</body>
</html>