Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reuse an object literal

I'm trying to reuse an object I created to dynamically create more than one slider on a page. My idea was to create an array and push my slider object there as often as needed, so I could access it by id. Unfortunatelly it doesn't work. Hope someone can point me in the right direction ...

So what I have is this;

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 up with different slider objects, add Ids to an 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 a function within the slider

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

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

But ... it's not working propperly when I call the init function inside the for loop more then once.

More weird, some functions calls seem to work, other have no effect. What am I doing wrong?

like image 210
user3605088 Avatar asked Feb 13 '23 01:02

user3605088


2 Answers

You can use Object.create.

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

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

If you return this from init your will be able to chain like:

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

However at this point I would just ditch the object literal and use constructors, since this is what you need.

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

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


var s1 = new Slider(...),
    s2 = new Slider(...);
like image 132
plalx Avatar answered Feb 15 '23 15:02

plalx


Write a function to return the object:

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

Then:

slide_array.push( slider() );

That'll give you a separate object every time. In you're version, you're filling the array with references to the same single object.

like image 45
Pointy Avatar answered Feb 15 '23 13:02

Pointy