Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9081211
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T20:15:42+00:00 2026-06-16T20:15:42+00:00

I’ve just started using Backbone.js and my test cases are churning up something pretty

  • 0

I’ve just started using Backbone.js and my test cases are churning up something pretty weird.

In short, what I am experiencing is — after I call a Backbone Model’s constructor, some of the fields in my object seem to come from a previously item. For instance, if I call:

var playlist = new Playlist({
    title: playlistTitle,
    position: playlists.length,
    userId: user.id
});

playlist.get('items').length; //1

however if I do:

var playlist = new Playlist({
    title: playlistTitle,
    position: playlists.length,
    userId: user.id,
    items: []
});

playlist.get('items').length; //0

Here’s the code:

define(['ytHelper', 'songManager', 'playlistItem'], function (ytHelper, songManager, PlaylistItem) {
    'use strict';
    var Playlist = Backbone.Model.extend({
        defaults: {
            id: null,
            userId: null,
            title: 'New Playlist',
            selected: false,
            position: 0,
            shuffledItems: [],
            history: [],
            items: []
        },
        initialize: function () {
            //Our playlistItem data was fetched from the server with the playlist. Need to convert the collection to Backbone Model entities.
            if (this.get('items').length > 0) {
                console.log("Initializing a Playlist object with an item count of:", this.get('items').length);
                console.log("items[0]", this.get('items')[0]);
                this.set('items', _.map(this.get('items'), function (playlistItemData) {
                    var returnValue;
                    //This is a bit more robust. If any items in our playlist weren't Backbone.Models (could be loaded from server data), auto-convert during init.
                    if (playlistItemData instanceof Backbone.Model) {
                        returnValue = playlistItemData;
                    } else {
                        returnValue = new PlaylistItem(playlistItemData);
                    }
                    return returnValue;
                }));

                //Playlists will remember their length via localStorage w/ their ID.
                var savedItemPosition = JSON.parse(localStorage.getItem(this.get('id') + '_selectedItemPosition'));
                this.selectItemByPosition(savedItemPosition != null ? parseInt(savedItemPosition) : 0);

                var songIds = _.map(this.get('items'), function(item) {
                    return item.get('songId');
                });

                songManager.loadSongs(songIds);
                this.set('shuffledItems', _.shuffle(this.get('items')));
            }
        },
        //TODO: Reimplemnt using Backbone.sync w/ CRUD operations on backend.
        save: function(callback) {
            if (this.get('items').length > 0) {
                var selectedItem = this.getSelectedItem();
                localStorage.setItem(this.get('id') + '_selectedItemPosition', selectedItem.get('position'));
            }

            var self = this;
            console.log("Calling save with:", self);
            console.log("my position is:", self.get('position'));
            $.ajax({
                url: 'http://localhost:61975/Playlist/SavePlaylist',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(self),
                success: function (data) {
                    console.log('Saving playlist was successful.', data);
                    self.set('id', data.id);
                    if (callback) {
                        callback();
                    }
                },
                error: function (error) {
                    console.error("Saving playlist was unsuccessful", error);
                }
            });
        },
        selectItemByPosition: function(position) {
            //Deselect the currently selected item, then select the new item to have selected.
            var currentlySelected = this.getSelectedItem();
            //currentlySelected is not defined for a brand new playlist since we have no items yet selected.
            if (currentlySelected != null && currentlySelected.position != position) {
                currentlySelected.set('selected', false);
            }

            var item = this.getItemByPosition(position);
            if (item != null && item.position != position) {
                item.set('selected', true);
                localStorage.setItem(this.get('id') + '_selectedItemPosition', item.get('position'));
            }

            return item;
        },
        getItemByPosition: function (position) {
            return _.find(this.get('items'), function(item) {
                return item.get('position') == position;
            });
        },
        addItem: function (song, selected) {
            console.log("this:", this.get('title'));
            var playlistId = this.get('id');
            var itemCount = this.get('items').length;

            var playlistItem = new PlaylistItem({
                playlistId: playlistId,
                position: itemCount,
                videoId: song.videoId,
                title: song.title,
                relatedVideos: [],
                selected: selected || false
            });

            this.get('items').push(playlistItem);
            this.get('shuffledItems').push(playlistItem);
            this.set('shuffledItems', _.shuffle(this.get('shuffledItems')));
            console.log("this has finished calling");

            //Call save to give it an ID from the server before adding to playlist.
            songManager.saveSong(song, function (savedSong) {
                song.id = savedSong.id;
                playlistItem.set('songId', song.id);
                console.log("calling save item");

                $.ajax({
                    type: 'POST',
                    url: 'http://localhost:61975/Playlist/SaveItem',
                    dataType: 'json',
                    data: {
                        id: playlistItem.get('id'),
                        playlistId: playlistItem.get('playlistId'),
                        position: playlistItem.get('position'),
                        songId: playlistItem.get('songId'),
                        title: playlistItem.get('title'),
                        videoId: playlistItem.get('videoId')
                    },
                    success: function (data) {
                        playlistItem.set('id', data.id);
                    },
                    error: function (error) {
                        console.error(error);
                    }
                });
            });

            return playlistItem;
        },
        addItemByVideoId: function (videoId, callback) {
            var self = this;
            ytHelper.getVideoInformation(videoId, function (videoInformation) {
                var song = songManager.createSong(videoInformation, self.get('id'));
                var addedItem = self.addItem(song);

                if (callback) {
                    callback(addedItem);
                }
            });
        },
        //Returns the currently selected playlistItem or null if no item was found.
        getSelectedItem: function() {
            var selectedItem = _.find(this.get('items'), function (item) {
                return item.get('selected');
            });

            return selectedItem;
        }
    });

    return function (config) {
        var playlist = new Playlist(config);
        playlist.on('change:title', function () {
            this.save();
        });
        return playlist;
    };
});

basically I am seeing the property ‘items’ is populated inside of initialize when I’ve passed in a config object that does not specify items at all. If I specify a blank items array in my config object, then there are no items in initialize, but this seems counter-intuitive. Am I doing something wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T20:15:43+00:00Added an answer on June 16, 2026 at 8:15 pm

    The problem is with using reference types (arrays) in the defaults object. When a new Playlist model is created without specifying an items value, the default is applied. In case of arrays and objects this is problematic, because essentially what happens is:

    newModel.items = defaults.items
    

    And so all models initialized this way refer to the same array. To verify this, you can test:

    var a = new Playlist();
    var b = new Playlist();
    var c = new Playlist({items:[]});
    
    //add an item to a
    a.get('items').push('over the rainbow');
    
    console.log(b.get('items')); // -> ['over the rainbow'];
    console.log(c.get('items')); // -> []
    

    To get around this problem, Backbone supports defining Model.defaults as a function:

    var Playlist = Backbone.Model.extend({
        defaults: function() {
            return {
                id: null,
                userId: null,
                title: 'New Playlist',
                selected: false,
                position: 0,
                shuffledItems: [],
                history: [],
                items: []
            };
        }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am using JSon response to parse title,date content and thumbnail images and place
I am using the SimpleRSS gem to parse a WordPress RSS feed. The only
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.