0

My problem is the following code! I want extend a jQuery Object to my XjQuery object and i seems to be work. but in the each function where i will find the object the function myfunc is not declared whats wrong here?

cheers and

sorry for my poor english

    XjQuery = function()
    {           
        var jq = $("<div id=xjq>hallo</div>");
        $.extend(this, jq);
    }
    XjQuery.prototype.myfunc = function() {
        this.append("<p>myfunc called</p>");
    }
    xjq = new XjQuery();

    xjq.myfunc(); // this works
    $("#maindiv").append(xjq); // works also 
    $("#maindiv").find("#xjq").each(function() {
        $(this).myfunc(); // doesn't work
    });
helmi
  • 61
  • 7

1 Answers1

2

Inside the each, this is a native DOM element, and $(this) is a jQuery object. You need to "convert" the jQuery object into your xjQuery object.

Why are you making an xJquery object in the first place? Why not make a jQuery plugin?

jQuery.fn.myfunc = function() {
    this.append("<p>myfunc called</p>");
};

Then you can do $("#maindiv").myfunc().

EDIT: To "cast" a jQuery object as a xjQuery object, you can modify the constructor like this:

XjQuery = function(jq)
{           
    jq = typeof jq === 'undefined' ? $("<div id=xjq>hallo</div>") : $(jq);
    $.extend(this, jq);
}

Then you can do:

$("#maindiv").find("#xjq").each(function() {
    new XjQuery(this).myfunc();
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 1
    Rocket is correct, the right way to add extensions to jQuery is via plugins. These extensions will show up as normal methods on the `$` object. For example `$('#a-div-id').myPluginMethod(anArgument, anotherArgument)` – James Andres Apr 20 '12 at 15:03
  • I forgot to mention, [jQuery documentation for plugins](http://docs.jquery.com/Plugins/Authoring). – James Andres Apr 20 '12 at 15:04
  • My extension its just an example i have more different objects that will be extended from jQuery and each object have different member functions – helmi Apr 20 '12 at 15:06
  • @helmi: The problem is still that you need to convert from jQuery to your "extended" objects. You can make a function to do that I guess, using `$.extend`. – gen_Eric Apr 20 '12 at 15:08
  • is there a posibility to cast the native object to my extended object – helmi Apr 20 '12 at 18:19
  • @helmi: You can edit your constructor to take a parameter, then use that. – gen_Eric Apr 20 '12 at 18:25
  • mhh have you a small sample or can you explain a i see you put the sample to the answer – helmi Apr 20 '12 at 18:33