Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve existing object into variable?

On my page I initially declare variable var as which creates an object through plugin using createAll... I'm referring to this plugin: http://kolber.github.io/audiojs/docs/

In order for plugin to work this object needs to be created. So after that I load some contact through ajax and plugin needs to be applied to this new content, so again I create this var as to create object, however now there are two similar objects on a page which conflict. I would like to know it there is a way where I can make var as that gets created after ajax call equal to existing object on a page?

I tried looking at what's inside var as by doing alert(as); This returns [Object object]

EDIT

This is what gets printed out with console log (This is original, first object)

Object

duration: 1
element: HTMLAudioElement
loadStartedCalled: false
loadedPercent: 0
mp3: null
playing: false
settings: Object
source: HTMLAudioElement
wrapper: HTMLDivElement
__proto__: Object

This is how objects are created, but I believe you need to know the plugin well to understand this

// Initialize audio js
      audiojs.events.ready(function() {
          var as = audiojs.createAll({


          });
});
like image 443
Ilja Avatar asked Nov 19 '25 21:11

Ilja


1 Answers

I've tested a working solution. Please note, the code is just to show it works - see my explanation below for specifics.

var as;
audiojs.events.ready(function () {
    as = audiojs.createAll();
});
$(document).ready(function () {
    setTimeout(function () {
        var mp3 = "http://s3.amazonaws.com/audiojs/02-juicy-r.mp3"; // audio.js example
        // creating new audio element, yours is probably added via ajax
        // [0] used to get DOM element instead of jQuery object.
        var audio = $('<audio/>', {id: 'test'}).appendTo('body').attr('src', mp3)[0];
        var testAS = audiojs.create(audio); // initialise new audio.js player
        as.push(testAS); // add "testAS" object to "as" array of objects
        console.log(as); // log "as" - now holds the original objects + "testAS"
    }, 5000); // timeout used for testing, above code can be in ajax success function instead
});

The mp3 and audio variables are just used as a demonstration as I don't know your ajax function's structure.

Audio.js has a .create() function which takes a single element as it's argument and returns an object. The original as variable is an array containing all the audio objects so you can just push the new object onto the end.

By defining as outside a function you make it global meaning that everything can access it and any new audio.js objects can be appended.

like image 197
Joe Avatar answered Nov 21 '25 10:11

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!