helmi
helmi

Reputation: 81

extend a jQuery Object to my own Object

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

Upvotes: 0

Views: 2078

Answers (1)

gen_Eric
gen_Eric

Reputation: 227220

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

Upvotes: 2

Related Questions