sam sam - 24 days ago 7
Javascript Question

How to convert jQuery code into a plugin? and plugin development patterns

I have developed the following jQuery code.

I have some questions:


  1. What is the best programming pattern to develop a jQuery plugin?

  2. How do I convert my code into a plugin? (I know it is possible to do what I am asking with
    $.fn.function
    , but what I don't understand is how to use it with an object.)

  3. Should I learn and master a single programming pattern or do I have to learn patterns, all exists?



Here is my HTML:

<ul class="linkContainer">
<li><a href="#" class="link" data-link="one">one</a></li>
<li><a href="#" class="link" data-link="two">two</a></li>

<div class="moreDetailsSection" data-section="one">
chakabakas
</div>
<div class="moreDetailsSection" data-section="two">
sasjakjk
</div>


And my JavaScript:

(function ($) {


var animation = {
options: {
linkContainer : $('.linkContainer'),
section: $('.section'),
link : $('.link'),
mainEffect: 'slideToggle',
mainEffectSpeed: 300
},

init: function (options) {
var link = this.options.link;

$.extend(this.options, options);
link.on('click', this.changeWindow );
},

changeWindow: function () {
var linkId = $(this).data('link'),
options = animation.options,
sectionContainer = animation.options.section,
elements = sectionContainer,
element = elements.filter('[data-section="'+ linkId +'"]');
element[options.mainEffect](options.mainEffectSpeed);

}

}

animation.init();


})(jQuery);


Demo

Answer

You already have a working plugin, just have jquery interact with it.

$.animation = animation;
$.fn.animation = function (options) {
    return this.each(function () {
        $.animation.init($.extend({
            link: this
        }, options));
    });
};

http://jsfiddle.net/8bmU6/1/

$.animation is just a reference to the original plugin, and $.fn.animation is a wrapper so that you can call $(".link").animation({options here})