Brodie
Brodie

Reputation: 8717

jQuery extending classes and functions issue

I've been looking around and I can't find a clear answer to my situation. So I'm making an iteration on an existing jQuery plugin jquery.autocomplete

So I have a jquery autocomplete plugin with a few things that I need to alter.

Step 1: Need to extend defaults (this works)

$.extend($.Autocompleter.defaults, customeDefaults);

This works, now I want to extend the functions where these defaults would get placed. My hangup involves this:

in the autocomplete I have a setup like this

$.Autocompleter.Select = function() {
    //a bunch of stuff in this class including:
    function init() {
      //this is the function that I need to extend.
    }
}

I attempted this

$.extend($.Autocompleter.Select.init, myChanges);

it didn't work Then I did a

console.log($.Autocompleter.Select.init());

and it produced a type error saying that Select had no method init... which it does. Any ideas?

Upvotes: 2

Views: 2452

Answers (1)

tjarratt
tjarratt

Reputation: 1690

The way that's currently setup, you can't extend the init function because it's not bound to the $.Autocompleter.Select object -- it's just declared as a function inside it.

Instead, if the function were defined like so, you could extend it:

$.Autocompleter.Select = function() {
    return {
      this.init() {
        //implementation
      }
    }
}

edit: Okay, after looking at the source there really is no way to extend the init function. You could probably extend the display method that calls init() and have it do what you want first, then call the original version. The method is very similar to the answer to this other question

var old_display = $.Autocompleter.Select.display;
$.Autocompleter.Select.display = function(args) { 
  //whatever you need to do first
  old_display.apply(this, args);
}

Upvotes: 2

Related Questions