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

Discovering the special HTML element lacking attributes

When two similar tags, such as anchor tags below, do not have any attributes or css properties associated between them, is there an internal property to distinguish between the two? <html> <body> <a>sample</a> <a>s ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

Having trouble with AngularJs and moment.js integration?

Looking to create a simple webpage using Angular Js for date calculations. Utilizing moment.js from http://momentjs.com/ Below is the current code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> ...

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

When using JavaScript to dynamically load canvases and create drawing contexts within a function, the context may suddenly disappear

Currently, I am modifying the canvases displayed through ajax calls and also updating what is drawn on each canvas. The primary issue I am facing is that my main drawing function fails on getContext and there are some unusual behaviors such as missing canv ...

Tips for stopping slide transition (moving to a different slide) in vue-slick-carousel?

I'm utilizing vue-slick-carousel to populate schedule data for a specific slide (in this case, a month). <vue-slick-carousel @afterChange="afterChange" @beforeChange="beforeChange" @swipe="swipe" class="te ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

The background image fails to display properly on the server in Next.js

Hello, I'm currently using NextJs and I have a challenge. I want to set a background image on the body element that is rendered server-side. Below you'll find my code snippets: First, here is my App.js: import BodyStyle from '@components/Bo ...

Troubleshooting PHP webpage with dysfunctional Python AJAX functionality

I have been working on developing a website that integrates with a python script to control GPIO pins on my Raspberry Pi. Unfortunately, I've encountered some issues with the code and need some assistance in troubleshooting. Could someone please revi ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

What is the best method for assigning a default value to the file input tag in HTML?

Can anyone help me with this code snippet? <input name="GG" type="file" value="< ?php echo $data['image'] ?>"> I was trying to set a default value in the form edit, but it seems to not be working. Does anyone know how to set a defau ...

Insert a new class within the container div

I am looking to insert a 'disabled' class within a parent div named 'anchorxx' The disabled class div can be located anywhere within the anchorXX divs Is it achievable using jquery? I am unsure how to approach this task. Appreciate y ...

Error: Unable to access attributes of an unknown variable (retrieving 'use')

I encountered an issue (TypeError: Cannot read properties of undefined (reading 'use')) while trying to execute the 'node server.js' command in the Terminal. The error points to my auth.routes.js file. This is the content of my 'a ...

Using Jquery to set values for css properties

I've recently started using jquery and I have a task related to a drop-down menu that I'm struggling with: if (scrnwidth <= 761) { if (display was block) { //Defaultly testi has display:none property. testi = m ...

How to Eliminate the Border on the Final Item within a React List

Hi everyone, I need help with removing the border of the last item in an unordered list when the list reaches a certain size. I initially tried this: document.querySelector('.employee-list-item:last-child').style.border = "none"; However, I enc ...

Utilizing JavaScript for manipulating arrays and displaying images

After asking this question previously without a satisfactory solution, I am hoping to provide better clarification. Imagine having an array with 3 items and it lands on 0 - a code is set up to display this in a div. Now, I want the image to be shown righ ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

Is it possible to customize the Menu hover effect in Element Plus and Vue?

Hello everyone, I'm a beginner with Vue, HTML, CSS, and Element Plus. I am trying to customize a Side Bar Menu with my own hover effect, but it doesn't seem to be working. Whenever I change the background color of the el-menu element, the hover e ...

Anchoring links on a webpage that provide users with a clear indication of their current position within the page

In the scenario of a single-page website with various sections (divs) and a header containing links to different anchors on the page, there is a desire to have an indicator highlight which anchor the user is currently viewing. An example of this can be s ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...