Search code examples
jquerypluginsprototypejs

prototype.js Element.addMethods


After getting a basic understanding about how a jQuery plugin is built, I've been looking to also convert it to Prototype.

I found this presentation here and on the Plugin/Extensions slide, it shows:

in jQuery: jQuery.fn.myPlugin = function(args) {return: this;};

in Prototype:

Element.addMethods({
  myPlugin: function(element) { 
  return element;
  }
});

I managed to convert my simple plugin to Prototype like this, but now I'm wondering if this is in fact the correct way to write it, or if one should actually use classes. I don't know much about classes in OOP, but googling about Element.addMethods didn't shed much light, too.

Many thanks!


Solution

  • Late reply, but based off your comments, I'd definitely create a class for this.

    Extending elements is useful when you want to perform an function relating to an element instance. Typically, at least with the ones that Prototype provides, these have more of a utility nature: changing attribute values, add/remove from dom, etc.

    I can't really imagine an element method that could encompass all the logic required for an accordion. You mentioned that you wanted to be able to have multiple accordions on the same page - that doesn't require it to be an element method. You can define an accordion class, then instantiate it for each spot you want to use it.

    Say your accordion class requires you to have one container div, and all the opening/closing tabs (or however you want to define them) are immediate descendants. Your markup would look like this:

    <div id="accordion1">
      <div class="slide"><!-- content --></div>
      <div class="slide"><!-- content --></div>
      <div class="slide"><!-- content --></div>
    </div>
    

    You'd setup your class:

    var MyAccordion = Class.create({
      initialize: function(containingElement) {
        var slides = $(containingElement).select('.slide');
        ... do all your other stuff, hook up event handlers to open/close, etc
      }
    });
    

    And instantiate it like so:

    new MyAccordion($('accordion1'));
    

    This will for sure let you have multiple instances. That's the whole point of using classes.

    If you were to extend Element to add methods, you'd have to do something like this to instantiate:

    $('accordion1').accordion();
    

    All your functionality would need to be in that one method, which seems less flexible than creating a class. It just feels a bit weird and wrong, too.

    Hope this helps. Let me know if you have any questions.