Efficiently caching and locally retrieving Backbone Models

Currently, my focus is on creating a dashboard using backbone and highcharts. In order to display different charts on the front end, I am utilizing a MySQL server as the backend source of all the necessary data.

The approach we are aiming for involves having a Backbone model that can perform a fetch operation, accepting parameters such as dateStart and dateEnd within the data object to retrieve the complete data set.

Upon receiving the data set from the server, the goal is to store it locally for caching purposes. This stored data will be used to graph various elements with Highcharts based on different filters. The data structure returned by the server consists of an array of objects as shown below:

{
    "dt": "2015-11-02",
    "ad_product": "product name",
    "environment": "mobile",
    "geo_code": "country name",
    "unique_users": "1",
    "impressions": "1",
    "all_engagements": "1"
  }

Users should have the ability to apply filters like ad_product, geo_code, metric, and environment on the front end. Based on these selections, I aim to query the backbone model data with the specified filters to generate the series array. This array will then be passed to the backbone view containing the Highcharts component.

I am currently exploring the best approach to achieve this functionality. Despite researching, I have not come across a definitive solution that aligns with my requirements effectively. Can anyone provide guidance on how to implement this seamlessly?

Answer №1

A backbone model acts as a data storage unit. Consider the following code structure for organizing your application:

var UserData = Backbone.Model.extend({
    initialize: function() {
        var user = this;

        $.ajax({
            url: '/user-data-api'
        }).then(function(data) {
            user.set(data);
            user.trigger('data:loaded');
        }).fail(function() {
            user.trigger('data:error');
        });
    }
});

var UserDashboard = Backbone.View.extend({
    initialize: function() {
        var dashboard = this;

        this.model.on('data:error', function() {
            console.log('There was an error loading user data');
        }).on('data:loaded', function() {
            dashboard.render();
        });
    },
    render: function() {
        this.displayCharts();
    },
    displayCharts: function(data) {
        data = data || this.model.toJSON();
        $('#chart-container').highcharts({
            // Chart configurations
        });
    },
    events: {
        'change .filter.type': function(e) {
            var selectedType = $(e.currentTarget).val(),
                data = this.model.toJSON()
            ;
            data = data.filter(function(entry) {
                return entry.type == selectedType;
            });
            this.displayCharts(data);
        }
    }
});

new UserDashboard({
    el: '#dashboard',
    model: new UserData
});

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

When attempting to use the POST method with a JSON body in Postgresql, I encounter an error

Encountering an error: There seems to be an issue with a JSON token at position 197 while trying to parse it. It occurs in the following code snippet: at JSON.parse () at parse (C:\Users\hp\empServers\node_modules\body-parser&bso ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

Is there a way to instruct npm to compile a module during installation using the dependencies of the parent project?

I am curious about how npm modules are built during installation. Let me give you an example: When I check the material-ui npm module sources on GitHub, I see the source files but no built files. However, when I look at my project's node_modules/mate ...

Guide to showcasing an image on an HTML page using HTTP header

I have an HTML page with a basic layout that includes a single button. When this button is clicked, it needs to trigger an HTTP request to a specific URL while including an Accept header for GET requests. The response from the HTTP URL will vary depending ...

Change the height of a <div> element to match the height of the window on a Bootstrap website

In my Bootstrap 4 website, I have a header, navbar, content-area, and footer. To see a live demo of the website, you can visit my JSFiddle link: https://jsfiddle.net/26zda5xv/2/ Check out the screenshot of the website here: https://i.sstatic.net/aMvH9.pn ...

Should one consider using the Express app.use() method within an asynchronous callback function?

Seeking advice on a recommended best practice. I recently developed an Express server that generates a JWT and sends it to the client whenever they hit an API endpoint. To maintain modularity, I separated the route handler into its own module and exporte ...

Tips for positioning a modal in the center specifically for zoomed-in mobile devices

I created a modal that uses the following function to center itself: center: function() { var top=Math.max($window.height() - $modal.outerHeight(),0) / 2; var left=Math.max($window.width() - $modal.outerWidth(),0) / 2; $modal.css({ ...

Customize your Shopify Messenger icon using JavaScript!

Shopify recently introduced a new feature that allows customers to contact store owners through messenger. My client has requested me to customize the appearance of this icon with their branded icon instead. https://i.stack.imgur.com/uytpd.png I have not ...

Laravel's Vue component is experiencing issues with loading Axios response data

Hey everyone, I hope you're all doing well! I'm facing a bit of an issue with passing data from an axios response to the data property. The data is successfully fetched from the database and displayed in the console, but when I try to display it ...

Notification for Pinned Tabs Update

Is there a method to emphasize pinned tabs in web browsers when receiving new notifications similar to Gmail, Facebook, or Twitter? The attached image should provide clarity on my query. I am seeking a solution that works across all browsers. ...

Is there a gentle approach to transferring calendar event variables in JavaScript?

The example provided below showcases a @model that contains data. To utilize specific portions of the data, I have transformed it into a Json object using Json.Serialize. This was necessary because the events:[ ] section requires data in a particular form ...

Coordinate Array Filtering from Different Coordinate Arrays

let big_coordinates_arr =[ [1,2],[3,4],[5,8],[7,9]] ; let small_coordinates_arr=[ [3,4],[7,9] ] ; Exepected Output: [ [1,2],[5,8] ] Hello everyone, I'm seeking assistance on filtering an array of coordinates based on another array of coordinate ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

I recently started exploring the world of creating discord bots using node.js, and I'm currently facing a bit of a challenge with it

As a beginner in the world of creating discord bots, I am currently focusing on developing commands. I recently followed a tutorial on Youtube which guided me through the process. The tutorial instructed me to use the following code snippet: const prefix ...

Enhance the Facebook Login popup with personalized settings

When a user clicks, a popup is triggered: FB.login(function () { // My CallBack }, { scope: 'email,user_birthday,user_location,user_hometown' }); This generates a Facebook login link with multiple parameters. I desire to inc ...

Ways to include items to various list items (`<li>`)

In the following code snippet, I am trying to create a list of options with checkboxes where each option name is contained within an li element: Currently, my code adds the checkbox and the name under the li instead of inside it. It looks like this: <u ...

A password-protected website scraper using Node.js

When using nodejs to scrape a website, everything works fine on sites without authentication requirements. However, when attempting to scrape a site with a login form, only the HTML from the authentication page is retrieved. I am able to get the desired HT ...

Using PHP, assign a reference to a class member

Trying to create a JSON server response in PHP has been quite the task. Using an array in my output to monitor errors and successes within the script has been helpful. Take a look at the code snippet below for a better understanding. <?php $output = ar ...

Struggling with Angular 8: Attempting to utilize form data for string formatting in a service, but encountering persistent page reloading and failure to reassign variables from form values

My goal is to extract the zip code from a form, create a URL based on that zip code, make an API call using that URL, and then display the JSON data on the screen. I have successfully generated the URL and retrieved the necessary data. However, I am strug ...

Issue with React useCallback not recognizing changes in dependencies caused by child functions

Can anyone lend a hand with this issue? I would greatly appreciate it. I've looked through previous questions but couldn't find anything quite like my situation. Here's the gist of it: I have a useCallback react hook that generates a set o ...