Storing Backbone collection data retrieved from a JSON file and persisting it in local storage

I recently started working with the backbone library and exploring building a mobile application using backbone, requirejs, and jquery-mobile. I've successfully populated my collection with data from a local JSON file (with plans to eventually retrieve it from a remote server). Now, my goal is to call this collection only once and then store it in localStorage for future reads. I'm attempting to utilize the adapter found here: https://github.com/jeromegn/Backbone.localStorage, but I'm struggling to understand how to implement it.

Sample code

// models
define([
  'underscore',
  'backbone'
], function(_, Backbone) {
  var AzModel = Backbone.Model.extend({
    defaults: {
      item: '',
      img:"img/gi.jpg"
    },
    initialize: function(){
    }
  });
  return AzModel;
});

// Collection
define(['jquery', 'underscore', 'backbone', 'models/az'], function($, _, Backbone, AzModel) {
    var AzCollection = Backbone.Collection.extend({
     localStorage: new Backbone.LocalStorage("AzStore"), // Unique name within your app.       
    url : "json/azlist.json",
    model : AzModel
    parse : function(response) {
         return response;
    }
});

return AzCollection;
});

define(['jquery', 'underscore', 'backbone', 'collections/azlist', 'text!templates/karate/az.html'], function($, _, Backbone, AzList, AzViewTemplate) {
    var AzView = Backbone.View.extend({
        id:"az",
        initialize: function() {
            this.collection = new AzList(); 
            var self = this;
            this.collection.fetch().done(function() {
                //alert("done")
                self.render();
            }); 

        },
        render : function() {
            var data = this.collection;
            if (data.length == 0) {
                // Show's the jQuery Mobile loading icon
                $.mobile.loading("show");
            } else {
                 $.mobile.loading("hide");
                console.log(data.toJSON());
                  this.$el.html(_.template(AzViewTemplate, {data:data.toJSON()}));
                  // create jqueryui
                 $(document).trigger("create");
            }
            return this;
        }
    });
    return AzView;
});

Could someone provide guidance on how to proceed with this implementation?

Answer №1

The functionality of the Backbone local storage adapter is crucial for managing data synchronization in your application. By overriding Collection.sync, you have the power to control how data is fetched from the server or saved locally. It's a powerful feature that gives you the flexibility to choose between server-side storage and local storage, but not both simultaneously.

There are two main approaches you can take:

  1. Start by fetching the data from the server using fetch, then set the Collection.localStorage property:

    var self = this;
    
    self.collection.fetch().done(function() {
        self.collection.localStorage = new Backbone.LocalStorage("AzStore");
        self.render();
    }); 
    
  2. Alternatively, set the Collection.localStorage property as usual and manually fetch the initial dataset using Backbone.ajaxSync (an alias for Backbone.sync within the localstorage adapter):

    Backbone.ajaxSync('read', self.collection).done(function() {
        self.render();
    });
    

The second option may be more favorable as it allows you to still retrieve data from the server when needed.

You can encapsulate this functionality within a method of the collection:

var AzCollection = Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage('AzStore'),
    refreshFromServer: function() {
        return Backbone.ajaxSync('read', this);    
    }    
});

Simply call this method when you want to fetch data from the server:

collection.refreshFromServer().done(function() { ... });

And use the native fetch method when utilizing local storage:

collection.fetch().done(function() { ... });

Updated to fix an error in the sample code for the convenience of those who come across it while searching online.

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

The best practices for utilizing getStaticProps with Firebase

I am completely new to Next.js and am struggling to make the getStaticProps function work properly. import firebase from '../firebase' export default function Home({ posts }) { return ( <div> <h1>All Posts</h1> ...

Sending data using JSON and HTTP POST method via URL

Is it possible for my servlet to receive 4 parameters through HTTP POST by using a URL? An illustration of the URL: http:///servlet The data that will be delivered will be in text form utilizing the JSON format. JSONObject myStr = new JSONObject(); I a ...

I am looking to implement the ajax data variable for use in a submit button. How should

I'm facing an issue where, upon clicking the submit button, I am unable to receive the value yearend. Instead, I am getting an undefined value. How can I ensure that I receive the correct yearend value when I click the submit button? Here is my code: ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

Struggling to extract content from a loaded gltf scene in Three.js?

I am trying to change the opacity or transparency of the material in a gltf loaded model. Despite looking at various examples, I am unable to locate any meshes. I have created this fiddle which indicates 'no mesh found'. Most examples I found fo ...

Tips for including a state in an API fetch request

Why does my API fetch work when the state is an empty string, but not when there is a string inside the state? Check out the examples below to see the issue. The concept is that the user inputs new text in an input field which updates the Search state and ...

Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return { scope: { ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

Searching for specific values within a date range in MongoDB, focusing on particular times of the day

I am working with a basic mongodb database that includes two key fields: date and value In my node project using mongoose, I have the following code to retrieve readings within a specific date range: Reading.find({ date: { $gte: startDate, $lt ...

Deleting JSON files using Discord and Node.js by requiring them from a specific folder

Currently, I am in the process of developing a Discord bot using Node.js. One of the functions within the bot utilizes JSON files to store information about specific entities. I aim to create a command in Discord that, when called with a specific name asso ...

Using Angular and nativeElement.style: how to alter cursor appearance when clicked and pressed (down state)

I am working with a native elementRef CODE: this.eleRef.nativeElement.style = "_____?????_____" What should go in "???" in order to apply the :active style to the element? (I want to change the cursor style when the mouse is clicked down, not when it is ...

Utilize JQuery to implement fading effects for clicked elements in a webpage

I've been using a rollover JavaScript plugin to create smooth transitional effects when users hover over clickable page elements. Everything was going well until I decided to switch to making ajax calls instead of page loads for dynamic content. The p ...

Using a jQuery UI dialog for multiple checkbox selection. The post array cannot be saved for a multi-select until the dialog is opened

CSS <td class="cell"> <a class="opener" id="opener_'.$iterator.'" href="#" rel="#type_dialog_<?= $iterator; ?>">Click here</a> <div id="type_dialog_<?= $iterator; ?>" name="t ...

What is the method for accessing the req, res objects within the callback functions?

One of my preferences is to access the req, res, next objects outside of the middleware function. For instance, in a sample middleware file called sample.js: var app = express(); .... ..... .... var updateUserInput = { init:function(){ get_data ...

What is the best way to transform an internal table of type LISTZEILE into a JSON or XML format?

I am faced with a requirement where I need to make Standard SAP reports accessible through Gateway services. For this purpose, I have leveraged the INST_EXECUTE_REPORT function module and the result of executing this FM with 'RM06ELLB' as input ...

In Vue JS, ensure that each item is loaded only after the previous item has finished loading

Is there a way to optimize the loading of around 1000 static images, .gifs, and videos for an online slideshow presentation? Currently, all items are loading simultaneously causing viewers to wait to see the first item. How can each item be loaded after th ...

Retrieve data from AJAX once the cycle is complete

Currently, I am attempting to calculate the sum of results from an external API by making a single request for each keyword I possess. The code is functioning properly; however, the function returns the value before all the ajax requests are completed. Eve ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...