In my plugin, I'd like to provide a constructor (or sorts) that
returns an extended jQuery object with some additional functionality.

I've reduced this problem down to a very simple test case.

I don't get an error until I attempt to run a method of the new,
extended object. The error is "foo.rename is not a function". This
apparently means that I was not successful in extending $(this) in the
plugin's constructor, but I'm not sure why. Does anyone know why?

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/
jquery.js" type="text/javascript"></script>
  <script type="text/javascript">
(function($)
{
  /* Extend the jQuery prototype so any selected element(s) can
implement create_content. */
  $.fn.extend
  ({
    /* Initialize this extended object. */
    create_content: function(settings)
    {
      /* Initialize all matched elements. */
      return this.each(function(i, el)
      {
        /* Extend $(this) with additional properties and methods. */
        $.extend(false, $(this),
          {
            s: settings,
            /* Show this content. */
            activate: function()
            {
              return this.show();
            },
            /* Hide this content. */
            deactivate: function()
            {
              return this.hide();
            },
            /* Change the content. */
            rename: function()
            {
              return this.html(settings["text"]);
            }
          }
        );
      });
    }, // end create_content
  }); // end $.fn.extend
})(jQuery);

$(document).ready(function()
{
  var foo = $("#foo").create_content({ text: "New text for
foo." }); // Error: foo.rename is not a function.
  var bar = $("#bar").create_content({ text: "New text for bar." });

  foo.rename();
  bar.rename();
});
</script>
</head>
<body>
  <div id="foo">Foo</div>
  <div id="bar">Bar</div>
</body>
</html>

Reply via email to