How can I reuse an object literal

I am trying to reuse the object I created to dynamically create more than one slider per page. My idea was to create an array and click on my slider object where necessary, so I could access it by id. Unfortunately this will not work. Hope someone can point me in the right direction ...

So, I have it;

var slider = {
  "init":function(slide_it){
    this.parent = $(slide_it);
    /Count Elements and create a navigation depending on the count etc./
  },
  "otherstuff":{...}
}

In my (document) .ready function, I create an array and fill it with different objects of the slider, add identifiers to the accordion and call the init function:

var slide_array = [];
var accordion_sections = $('#accordion > div').length;
for(var i = 0; i < accordion_sections; i++){
  slide_array.push(slider);
  $('#accordion').children('div').eq(i).attr('id', 'slide_it_'+ i);
  slide_array[i].init($('#slide_it_' + i).find('.slider'));
}

Then I have a button with class = "next" and I call the function inside the slider

$('.next').click(function(){
  slide_array[0].otherstuff();
});

My plan is to get the parent .next element and its id so that I can use slide_array[parentID].otherstuff();

... , init for .

, , . ?

+4
3

Object.create.

var s1 = Object.create(slider),
    s2 = Object.create(slider);

s1.init(...);
s2.init(...);

this init, , :

var s1 = Object.create(slider).init(...);

, , .

function Slider(slide_it) {
    this.parent = $(slide_it);
}

Slider.prototype = {
    constructor: Slider,
    otherStuff: function () {}
};


var s1 = new Slider(...),
    s2 = new Slider(...);
+4

:

function slider() {
  return {
    "init":function(slide_it){
      this.parent = $(slide_it);
      /Count Elements and create a navigation depending on the count etc./
    },
    "otherstuff":{...}
  };
}

:

slide_array.push( slider() );

. .

+2

jQuery?

jQuery.fn.slider = function(options) {
    return this.each(function() {
        var sliderElem = $(this),
            settings   = $.extend({
                speed : 3000,
                something : 'other thing'
            }, options);

        otherStuff(sliderElem);
    });

    function otherStuff(elem) {

    }
}

$('#accordion > div').slider();

, ?

+2

Source: https://habr.com/ru/post/1539313/


All Articles