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
    });

1 Answer 1

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

7 Comments

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)
I forgot to mention, jQuery documentation for plugins.
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: 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.
is there a posibility to cast the native object to my extended object
|

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.