1

I have the following code:

// auto_suggest.js
function AutoSuggest(textboxElem, resultElem, url) {
    this.textboxElem = textboxElem;
    this.resultElem  = resultElem;
    this.url         = url;
    this.registerEvent();
}

AutoSuggest.prototype = {
    registerEvent: function() {
        this.textboxElem.onkeyup = this.getSuggestions;
    },
    getSuggestions: function() {
        // This doesn't work either: this.loadResponse("some data");
        $.get(this.url, { text: this.textboxElem.value }, this.loadResponse);
    },
    loadResponse: function(data) {
        // Not called
        this.resultElem.innerHTML = data;
    }
};

// suggest.html
<script src="jquery-1.6.1.js" type="text/javascript"></script>
<script src="auto_suggest.js" type="text/javascript"></script>

<script>
$(function() {
    var suggest = new AutoSuggest(document.getElementById("suggest"), 
                                  document.getElementById("result"), 
                                  "result.txt");
        // This DOES work: suggest.loadResponse("123");
});
</script>

<input type="text" id="suggest" /><br>
<div id="result"></div>

The function loadResponse refuses to be called from within the object, but from the outside it is fine. What could be the problem?

2
  • I don't understand the problem. suggest.loadResponse("123"); should work from outside the object, this.loadResponse("123"); from within.... Commented Jun 9, 2011 at 18:10
  • Does AutoSuggest.loadResponce work? Commented Jun 9, 2011 at 18:11

2 Answers 2

3

The AJAX callback (AutoSuggest.loadResponse) is, by default, passed the jqXHR object as its context (this value). You need to override this by passing the context option to $.ajax. Replace your $.get function with this:

$.ajax({
    url: this.url,
    type: 'GET',
    data: { text: this.textboxElem.value },
    success: this.loadResponse,
    context: this
});

This makes jQuery set this to the correct value.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Alternatively, you could use $.proxy(). $.get(this.url, { text: this.textboxElem.value }, $.proxy(this,"loadResponse"));
0

The code

this.textboxElem.onkeyup = this.getSuggestions;

should be

var t = this;
this.textboxElem.onkeyup = function() {
    t.getSuggestions();
}

Comments

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.