How to access object method within jQuery event
I'm trying my hand 开发者_Python百科in designing an application in JavaScript that is object oriented with help from jQuery. However, I've run into issues when using the jQuery event handlers within my application's class. Here is the offending snippet of code:
<script type="text/javascript">
function Library(s_list) {
this.songs = s_list;
this.song_table = $('#songs');
this.search_input = $('#search-txt');
this.refresh_table = function() {
this.song_table.html('<tr id="fields"><td></td><td>Name</td><td>Artist</td><td>Album</td><td>Time</td></tr>');
for ( index in this.songs ) {
if ( (index % 2) == 0 ) {
this.song_table.append('<tr class="l"><td></td><td>' + this.songs[index] + '</td><td>Artist</td><td>Album</td><td>Time</td></tr>');
} else {
this.song_table.append('<tr class="d"><td></td><td>' + this.songs[index] + '</td><td>Artist</td><td>Album</td><td>Time</td></tr>');
}
}
}
this.filter_songs = function(text) {
// Not implemented
}
this.search_input.keyup(function() {
var sender = $(this);
var s = $.trim(sender.val());
// I need to access the filter_songs method of the Library class here. Normally I would use "this" but jQuery uses it for the html object that triggered the event
});
this.refresh_table();
}
var library;
$(document).ready(function() {
library = new Library(song_list);
});
</script>
The problem is I need to access the filter_songs method of the Library class from the jQuery search_input.keyup event handler. Normally I would use "this" but jQuery uses it for the html object that triggered the event. Am I approaching the design of this application wrong, or is there a way to fix this issue? Thanks for the help.
You need a closure. Try this:
var self = this;
this.search_input.keyup(function() {
var sender = $(this);
var s = $.trim(sender.val());
self.filter_songs(s);
});
精彩评论