Search code examples
javascriptbackbone.jsiframe

BackboneJs how to loop through collection get specific value from each model


I have a Backbone Collection where I want to get a specific value from each model and then insert that value into an Iframe.

So, I have multiple Iframe's, where I want to insert the data-src dynamically, the basic code for the iframe is:

<iframe class="playlist" data-src=""></iframe>

and my Backbone Code:

this.collection.each(function(spotify) {
    var service = spotify.get('services').spotify;
    var spotifyplayId = service.substr(service.lastIndexOf('/') +1);
    console.log(spotifyplayId)
    $('iframe.playlist').each(function(spotifyplayId) {
        $(this).attr('data-src', 'https://embed.spotify.com/?uri=spotify:user:digster.dk:playlist:'+ spotifyplayId);
    });
});

the console.log(spotifyplayId) gives me the correct data, only the dynamic insert into the Iframes fails. What am I doing wrong?


Solution

  • Try this

    this.collection.each(function(spotify, index) {
        var service       = spotify.get('services').spotify,
            spotifyplayId = service.substr(service.lastIndexOf('/') +1);
    
        $('iframe.playlist').eq(index).attr('data-src', 'https://embed.spotify.com/?uri=spotify:user:digster.dk:playlist:' + spotifyplayId);
    });
    

    Because in your example spotifyplayId is index (0, 1, 2) in loop, but you need get spotifyplayId from parent scope. And in our case better use .eq instead of $.each.