2

I'm trying my hand 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.

1 Answer 1

3

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);
        });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That was just what I needed. It was an obvious solution but I guess my brain isn't working well today.
:) we'll go thru cloudy days!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.