Reputation: 986
I'm trying to get rid of that nasty variable declaration of ref in this instance, I'm sure there is a way to get out of the each scope to get the "this" of the on-call. I just have no idea how to.
$(document).on('click', '.item', function(){
var ref = $(this).attr('data-id');
$.each(t, function(){
if(this.id == ref){
//action
return false;
}
});
}
This isn't really life or death, I just am trying to clean up code.
Upvotes: 1
Views: 246
Reputation: 5608
Actually there is something you can do. You can bind your function to a context. Since you're using jQuery already you can use jQuery.proxy which takes in parameters function and context, binds that function to that context and return a new function.
Read this so you'll understand it a bit: http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/
Then take a look at this: http://api.jquery.com/jQuery.proxy/
Hope this helps a bit... :)
Upvotes: 3
Reputation: 12115
There is a way to do this: use the event
reference passed to the event handler automatically.
$(document).on('click', '.item', function(e) {
$.each(t, function(){
if (this.id == $(e.target).attr('data-id')) {
//action
return false;
}
});
}
But, that doesn't buy you anything except more time to do other things while the code runs. ;)
Upvotes: 3
Reputation: 2278
Not sure what your intention is but if it's to simply reference this original element:
$(document).on('click', '.item', function(){
var that = this;
$.each(function(){
// use 'that' however you'd like
if ($(that).data().id == 'whatever') ...
}
});
You can not "leave" a scope in javascript, you can merely reference declarations in parent scopes.
Upvotes: 1