Javascript wrapper error?

I want to add functionality to a jQuery method.

I have code

$('li.s').appendTo('#target');

      

There are several elements that match li.s

and I can see how it grabbed Firebug correctly.

The method append

works fine without my shell. However, with my wrapper (which shouldn't change anything about the function):

var oldAppend = $.fn.append;

$.fn.append = function(expr) {
    return oldAppend.call(this, expr);
};

      

The correct jQuery object is returned, but instead #target

only the first is added li.s

, not all. Why is this? Where do I lose other items when called oldAppend

?

+1


a source to share


2 answers


The problem is that you (I) mark the passing of all arguments sent append

to appendTo

. Use apply

and arguments

like this:

var oldAppend = $.fn.append;

$.fn.append = function() {
    return oldAppend.apply(this, arguments);
};

      



(Remember, all functions have arguments

, so you need var args = arguments

an appropriate accessor scope to access those arguments, for example when using $.each

.)

0


a source


I haven't gone into the jQuery code to test this, but most functions should usually return this.each (fn):

$.fn.append = function(expr) {
    return this.each(function() {
        oldAppend.call($(this), expr);
    });
};

      



You will notice that I had to wrap this

a jQuery object inside an inner function as the append method expects this to be a context. I'm not sure, but you might find that you also need to wrap the external reference in this

:

return $(this).each

      

0


a source







All Articles