2

I'm trying to extend jQuery with the following:

$.fn.extend({
    initCore:   $.fn.init,
    init:       function (selector, context, rootjQuery) {
        return $.fn.initCore(selector, context, rootjQuery);
    }
}),

However, it doesn't seem to work right, and creating simple things such as an alert on click produce errors. Can anyone spot the problem?

Thanks in advance!

jleck
  • 821
  • 1
  • 8
  • 14

2 Answers2

4

$.fn.init is the class constructor itself.

Try adding $.fn.init.prototype = $.fn afterwords to restore the original prototype.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Yes, but even then you can't use `return $.fn.initCore(...)` – Bergi Jun 21 '12 at 21:09
  • It seems to work. I've prototyped the fn object though, so initCore will always be there to run, and I'm passing through the original parameters. Surely that's all that is needed? – jleck Jun 21 '12 at 21:16
  • Oh sorry, I see what you mean. I already changed $.fn to this.fn for it to work! – jleck Jun 21 '12 at 21:17
1

I guess you're missing the context. Try

return $.fn.initCore.call(this, selector, context, rootjQuery);

or even easier

return this.initCore(selector, context, rootjQuery);

No, wait, init is the constructor itself. That means

$.fn.initCore.call(this, selector, context, rootjQuery);
doSomeThingWith(this);

...

$.fn.init.prototype = $.fn;

or

var ob = new $.fn.initCore(selector, context, rootjQuery);
doSomeThingWith(ob);
return ob;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I fixed it by just putting $.fn.init.prototype = $.fn :) Thanks! – jleck Jun 21 '12 at 21:08
  • I don't think that's all. You are still calling `$.fn.initCore` with no context, which will lead to awfull errors. – Bergi Jun 21 '12 at 21:11