What's the best approach: Backbone-Relational discovery or retrieval?

Although the model caching feature in Backbone-Relational is effective, loading a simple model securely requires considerable code. For example:

// Attempt to locate a model in the cache
this.model = MyModel.find({id:id});

if(this.model){
    // Model retrieved from cache, perform an action.
    this.doSomething();
}else{
    // Load the model and then carry out an action upon success.

    var self =  this;

    this.model = new MyModel({id:id});
    this.model.fetch({
        success: function(){
            self.doSomething();
        }
    });
}

Perhaps creating a utility function could simplify this process, as it currently seems too elaborate.

Answer №1

Consider this scenario: the side effect is that the discovered item will be refreshed to match the server's version, resulting in a server request being made regardless. This negates the whole purpose of caching.

this.model = MyModel.findOrCreate({id:id}).fetch({
    success: function(){
        self.doSomething();
    }
});

Answer №2

It seems like the task at hand involves typical mysql/database work.

You might consider restructuring the code in this manner:

this.model = MyModel.find({id:id});

try {
    this.doSomething();
} catch (e) {
    if (e instanceof SomeSpecificException) {
        var fetchPromise = this.model.fetch();
        fetchPromise.done(
            this.doSomething.bind(this)
        );
    }
}

Explaining the code snippet:

The try/catch statement is useful for identifying when something is not found or does not exist. If an error is caught, then a fetch operation can be initiated. The fetch should return a future/promise; if it doesn't, you can create a shim to handle it accordingly. Once the promise is resolved, it will call the doSomething function with its scope bound to 'this', eliminating the need for 'self'.

How to create a shim:

A potential solution could be:

var Deferred = require('simply-deferred');

Backbone.Model.prototype.fetch = function(options) {
   var dfd = Deferred();

   Backbone.Model.prototype.fetch.call(
       this, 
       _.extend({ success: dfd.resolve.bind(this) }, options)
   );

   return dfd.promise;
}

The only uncertainty lies in which function to utilize; using Backbone.Model.prototype.fetch may refer to the original Backbone fetch method. The goal is to invoke the Backbone-Relational fetch method, passing your options and scope, while ensuring the success option resolves the promise.

Why isn't this functionality built-in? Well, individuals in the node.js community opted against making promises the default approach, potentially leaving developers dealing with callback hell.

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

How can we convert unpredictable-length JSON user input into well-structured HTML code?

Welcome to the world of web development! I am currently embarking on a project where I aim to transform JSON data into HTML structures. Specifically, I am working on creating a dynamic menu for a restaurant that can be easily updated using a JSON file. The ...

Uncover the structure of a regular expression pattern to discover the quantity of tokens and the size of the anticipated matches

I am looking to validate certain fields in my forms by determining the number of tokens and length specified by a particular regular expression. For example, For the pattern [0-9]{3},[0-9]{2}, I need to identify 5 as the length and 2 as the number of to ...

Adding a refresh feature to ui-sref in markup

Is there a way to include the reload option in a ui-sref markup without using the javascript function directly? <a ui-sref="app.editPost({new:true}, {reload:true})">new post</a> I've tried this approach, but it doesn't seem to be wo ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

Locate all elements in an array that contain a particular value for a specific key using Javascript

In my JavaScript data, I have two arrays: ARRAY ONE: [ TextRow { v_id: 3000 }, TextRow { v_id: 3001 }, TextRow { v_id: 3002 } ] ARRAY TWO: [ TextRow { s_id: 'S001', v_id: 3000, type: 'control' }, TextRow { ...

Is it necessary to implement clustering for each route in an Express.js application?

Currently, I am utilizing the cluster module to fork my application within my index.js, which serves as the primary file in the root directory of my website. My application consists of numerous routes. Should I incorporate the cluster code to encapsulate a ...

Building a dynamic form using React Material-UI Autocomplete and integrating it with react

I'm encountering an issue where the MUI Autocomplete is not displaying the selected fields even though the react-hook-form values have been updated. Here is the code snippet import { useForm, Controller, FormProvider } from "react-hook-form" ...

issue with manipulating URLs in Express routing

Looking for assistance with Express routing. I want users to only see localhost:3000/page2 when they go to /page2, instead of localhost:3000/page2.html I have three HTML pages - page1.html, page2.html, and page3.html. I've created a server using Expr ...

Using `ng-model` within an Angular directive

Looking to achieve bi-directional binding in an Angular directive Here is my current approach: angular.module('myapp',[]),directive('mydirective', function() { var directive = {}; directive.restrict = 'E'; directi ...

HTML: Determine the Precise Location of a Div Element That is Centered

Imagine I have this image: Is there a way for me to determine the x/y or left/top properties of my canvas if it is centered using the following CSS: #canvas-container { width: 100px; height:100px; margin: 0px auto; } Note ...

Sorting elements in an array using jQuery is a common task that can be easily accomplished

Query: I am faced with a challenge in handling a table where rows are dynamically added upon button clicks. To allow users to rearrange the rows, I have incorporated the jquery-ui sortable() function for sorting purposes. Consider the following scenario: ...

Leveraging AJAX for fetching files on the identical server

Just starting out with HTML and AJAX programming, so let's give it a shot: I've developed a website that populates a table with content from an external txt file (content.txt). The text file is hosted on a Windows 2003 webserver in the C:\I ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

Tips for Embedding External JavaScript and URLs in Joomla Protostar Template

I'm interested in incorporating a hamburger menu into my Joomla protostar template, similar to the one featured on this URL: ['https://codepen.io/PaulVanO/pen/GgGeyE'] This will provide me with a fullscreen hamburger menu for both desktop ...

Verify if a personalized angular directive is able to display or conceal an element

I have a custom directive that toggles the visibility of an element based on the value of another service. I attempted to write a test to verify if the directive functions as intended. Initially, I used the ":visible" selector in my test, but it consistent ...

Ways to showcase JSON data with jQuery

My code displays movie data from a JSON variable and populates it on a dropdown list based on the selected city. I aim to include show timings along with other details from the JSON content. The code snippet is as follows: $(document).ready(function() ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...

Having trouble parsing the body parameter in Express for a POST request

I am encountering difficulty in accessing the body parameters of a request using Express: const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const app = express(); con ...

Best practices for displaying code blocks within an AngularJS application

Currently, I am in the process of building a website focusing on AngularJS within AngularJS ;-) To accomplish this, I have included ng-app within the body element. As a result, all my code snippets (enclosed in <pre><code> ... </code>&l ...

Display the number of items that have been filtered as soon as the Mixitup page loads

Currently, I am utilizing MixItUp 3 for sorting and filtering items, with the goal of displaying the count of items within each filter category upon the initial page load. Despite attempting a solution found on SO (mixitup counting visible items on initial ...