Exploring the connection between Backbone.js and the localStorage plugin through the 'todo' example, focusing on the relationship between collections and models

Check out this official sample app:

I'm puzzled by the connection between the collection and its property localStorage = new Store(..)

Shouldn't this belong in the model since you can't really do a collection.save() anyway?

Furthermore, I attempted to implement something similar, but encountered issues

var Person = Backbone.Model.extend({
        defaults: {
            name:'no-name',
            age:0
        }
});


var Persons = Backbone.Collection.extend({
        model: Person,
        localStorage: new Store('Persons'),
        initialize: function(){
            console.log('collection initialized');

        }
});

window.people = new Persons();

var p1 = new Person({name:'JC',age:24});
p1.save({text:'hello'}); //<--- Uncaught TypeError: Cannot read property 'localStorage' of undefined

Any guidance on resolving this dilemma would be appreciated.

Answer №1

One key aspect is utilizing the .create() function within a collection to facilitate saving data to localStorage.

Check out the source code for a todo sample here:

createOnEnter: function(e) {
      var text = this.input.val();
      if (!text || e.keyCode != 13) return;
      Todos.create({text: text});
      this.input.val('');
    },

This feature then grants the model instance the ability to modify it by employing the .save({attr:value}) function.

If modelInstance.save() is called without specifying a localStorage property in the model's constructor function, an error message will pop up:

Uncaught TypeError: Cannot read property 'localStorage' of undefined

However, with the model now stored in localStorage via the collectionInstance.create() method, you can use modelInstance.save({attr:value}) to make changes.

To sum it up, while Models offer the save() function for persistence, Collections provide the create() function for the same purpose.

In order to utilize these functionalities, ensure that REST urls are configured correctly within the collection and model or initiate the localStorage plugin within the Constructor Function of either (depending on your setup).

Answer №2

Dealing with a similar issue where I needed to save a collection loaded from LocalStorage, I implemented a save() method on my Collections that iterated through each model and triggered model.save().

MyCollection.save = ->
    @each (model) ->
        model.save()

However, there was a downside to this approach when using Backbone.LocalStorage. By simply removing a model from the collection at runtime, it wasn't deleted from local storage. Manually handling unmatched models for destruction somewhat undermined the purpose of Backbone.Collection.set(); which offers features like adding/merging/deleting.

To address this issue, one solution involved modifying Backbone so that Backbone.Collection.set() used destroy() instead of remove() for missing models. Another approach I took was having all models listen for their own 'remove' event and trigger their own 'destroy' method accordingly, making removals permanent.

class Model extends Backbone.Model
  initialize: ->
    @on 'remove', @destroy

These solutions meant that removing a model equated to permanently destroying it, which suited my needs. To customize this behavior, special conditions could potentially be created to manage model removal differently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the issue with the variable in the CSS code?

I established a var variable called --item-width in JavaScript. I assumed it would function correctly in the CSS, but unfortunately, it's not working as intended. What steps should I take next? Being a novice, I probably made a mistake somewhere. Your ...

Tips for displaying content within a directive in different locations

I am looking for a way to create a component directive that will render the content placed inside its selector at specific sections within its HTML structure. The sections I want the content to be rendered in are header, footer, main. This is the example ...

Tips for resizing mesh along the global axis

Have you ever used an online 3D editor that allows you to manipulate individual meshes by moving, scaling, and rotating them? This editor utilizes custom transform controls inspired by the TransformControls code from three.js. Here is a snippet of code fro ...

Using Ajax, transmit an array from javascript to a php function

How can I send an array from JavaScript to PHP using AJAX? I'm not sure how to do this, especially when trying to send it to a PHP function like a controller class. Can someone please correct me if I'm wrong? Below is my current JavaScript code f ...

Exploring creative art with Three.js streaming

I'm seeking advice on the best way to handle a large amount of data from a stream in Three.js, without needing to store it in memory for the entire application's lifespan. In traditional WebGL, this is typically achieved with gl_drawArray. Howev ...

The URL for the Ajax request is unexpectedly filled with strange data

My current request looks like this: $.get("getdataforcharts", {q: ["test"]}, function (response) { alert( "success" ); }).done(function() { alert( "second success" ); }); I am expecting the URL to be: /testpage/getdataforcharts?q=t ...

Scroll function not functioning properly in Internet Explorer

When attempting to use scroll(x,y) in Internet Explorer 10 with JavaScript, I encountered an issue when trying to run the script on a website. Is there an alternative method that works for IE? This is part of a Java Selenium test where I need to scroll wit ...

The attempt to convert the value "NaN" to a number (data type number) at the specified path "markupPercentage" was unsuccessful

When I try to use Excel to update products, I encounter an error related to the presence of NaN. Here is the specific error message: CastError: Cast to Number failed for value "NaN" (type number) at path "markupPercentage" messageFormat: undefine ...

Choosing Between Partial View with ng-route or ng-show/ng-hide: Which One is the Better Choice?

In my app, I have multiple tab views (four to five) where clicking on each tab will display content based on the tab selection. After trying two approaches - ng-route and ng-show/ng-hide, I found that ng-show/ng-hide is more efficient in terms of performa ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

Ways to extract the names of a JSON object using Angular

In my dataset, I have information about block devices with specific attributes such as Backend_Device_Path, Capacity, Bytes_Written, etc. $scope.mydata = [{ "Block_Devices": { "bdev0": { "Backend_Device_Path": "/dev/ram1", ...

The Nodejs express static directory is failing to serve certain files

Hello everyone, I'm currently working on a project using NodeJs, Express, and AngularJS. I've encountered an issue where my page is unable to locate certain JavaScript and CSS files in the public static folder, resulting in a 404 error. Strangely ...

Error encountered in React Native PagerView due to webpack on web platform

Currently, I'm utilizing the PagerView component from 'react-native-pager-view' available at https://github.com/callstack/react-native-pager-view. A quick background on my app - it aims to be accessible on Android, iOS, and web platforms. A ...

The error message you are encountering is: "Error: Unable to find function axios

Can't figure out why I'm encountering this error message: TypeError: axios.get is not functioning properly 4 | 5 | export const getTotalPayout = async (userId: string) => { > 6 | const response = await axios.get(`${endpoint}ge ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Retrieve a single instance of every element within an array using JavaScript

I have an array of player objects, each containing properties such as "position" and "player_name". With 8 unique positions available for players, I aim to extract the first player for each position and transfer them to a new array. This way, the new array ...

Unable to perform the GET request method due to data indicating [object object]

Currently, I am attempting to use a get request method within both Vue and Express in order to retrieve data based on my v-model. Displayed below is the code where I am trying to send the data to Express. getResult() { axios .get( `${process. ...

In JavaScript, locate the closest element in an array based on its value, avoiding cases where the value exceeds the nearest element

I am trying to find the nearest element in an array based on a given value, but I specifically want it to be the nearest one that is greater than or equal to the value. For example, if I have an array like [3000, 5000, 8000], when I search for a number bel ...

Issue with Phonegap FileTransfer functionality

Currently, I am working on building a basic iPhone app using phonegap and jquery. My main goal is to be able to successfully upload images from my iPhone to a remote server. I attempted to achieve this by utilizing the phonegap FileTransfer feature, but ...

Stopping a Firefox addon with a button click: A step-by-step guide

Utilizing both the selection API and clipboard API, I have implemented a feature in my addon where data selected by the user is copied to the clipboard directly when a button is clicked (triggering the handleClick function). However, an issue arises when a ...