Reputation: 8785
I'm writing a class that needs to attach event listeners to objects within a respective sections (#one and #two in this example), but I'm having issues passing variables from the class to set up the jQuery event listeners.
<script type="text/javascript">
function myClass(id) {
this.id = id;
$(document).ready(function(){
$(this.id + ' .filter').click(function(){ alert("You clicked a filter"); });
});
}
one = new myClass('#one');
two = new myClass('#two');
</script>
<div id="one">
<a href="javascript://" class="filter">I am link one</a>
</div>
<div id="two">
<a href="javascript://" class="filter">I am link two</a>
</div>
... unfortunately variable scope doesn't agree with me; this.id
cannot be accessed from within $(document).ready()
, and so the event listeners don't fire. How can I access it?
Upvotes: 1
Views: 1609
Reputation: 66201
In this case, you don't need to declare it in another variable at all, just swap out id
for this.id
in your document.ready
function:
function myClass(id) {
$(document).ready(function(){
$(id + ' .filter').click(function(){ alert("You clicked a filter"); });
});
}
However, if you did some processing to it, you could always alias this
in another variable:
function myClass(id) {
var base = this;
base.id = id;
// Other items set on base.value
$(document).ready(function(){
$(base.id + ' .filter').click(function(){ alert("You clicked a filter"); });
});
}
Upvotes: 0
Reputation: 29267
You need to make a local
copy of this
to use it inside inner functions:
function myClass(id) {
this.id = id;
var that = this;
$(document).ready(function(){
$(that.id + ' .filter').click(function(){ alert("You clicked a filter"); });
});
}
Upvotes: 0
Reputation: 44191
This is because "this" is a keyword which references the object on which the current function was invoked. With jQuery event handlers, this object is the DOM element on which the event hander was registered (i.e. document in this case.) Use a different variable name to store your object:
<script type="text/javascript">
function myClass(id) {
var me = this;
this.id = id;
$(document).ready(function(){
$(me.id + ' .filter').click(function(){ alert("You clicked a filter"); });
});
}
one = new myClass('#one');
two = new myClass('#two');
</script>
Upvotes: 1