开发者

Cannot call extended method on JQuery object

开发者 https://www.devze.com 2023-03-22 05:34 出处:网络
I have HTML something like the following: <div id=\"quoteContainer\"> <div class=\"quote prototype\"></div>

I have HTML something like the following:

<div id="quoteContainer">
    <div class="quote prototype"></div>
     <div class="quote live q0"></div>
     <div class="quote live q1"></div>
     <div class="quote live q2"></div>
     <div class="quote live q3"></div>
     ...
</div>
开发者_开发百科

Where each of the live divs are coppies of the prototype div. Here is the code that makes the copy:

quote = $(".quote.prototype").clone().show()
        .removeClass("prototype").addClass("live")
        .addClass(foo)
        .appendTo("#quoteContainer");

$.extend(quote, QuoteCalculator);
quote.setQuoteClass(foo);

Foo is a variable that combines "q" and the number of quotes. The QuoteCalculator class has several methods which I want to call, including (ex.) shout(). Here is part of QuoteCalculator:

var QuoteCalculator = {
    ...

    shout: function() {
        console.log("hello from calculator");
    },

    ...
};      

At another point in the program, I want to call the shout method. Here is my code:

$(".quote.live").each(function() {
      this.shout();
});

Here is what firebug says: this.shout is not a function [Break On This Error] this.shout();

EDIT: Here is the weird part: calling quote.setQuoteClass(foo) does not generate an error. On the contrary, it works perfectly.

Why does the problem occur, what causes it, and how do I fix it?


Your extend:

$.extend(quote, QuoteCalculator);

is extending an instance of the jQuery function. It is not extending the jQuery prototype such that any new queries on elements that had been in the previous collection (quote) also get the methods.

$(".quote.live")

^^ that is a new query, resulting in a new instance of jQuery which is not connected to the instance you stored in quote which you extended.

You need to look into plugin authoring and how to extend the jQuery "class" (the prototype of the jQuery function) so that all instances of jQuery returned by the factory have the methods you want.


It looks like you're expecting quote to be the DOM object - instead, it's a jQuery object referring to the DOM. Try this:

$.extend(quote.get(0), QuoteCalculator);
0

精彩评论

暂无评论...
验证码 换一张
取 消