Using Backbone: Leveraging a custom extended model when fetching a collection

Currently, I am working on developing a custom Wordpress theme using technologies like Javascript, Requirejs, and Backbonejs. As part of this process, in the index route, I have set up a new postsCollection

app.postsCollection = new Posts.Collection();
to store all WordPress posts. Subsequently, I call .fetch()
app.postsCollection.fetch( { success: ..., error: ... } );

Below is the code snippet from my modules/posts/collection.js file :

define( function( require, exports, module ) {

"use strict";

var app       = require( 'app' );
var PostModel = require( './model' );

var PostsCollection = Backbone.Collection.extend( {

    model   : PostModel,
    url     : app.jsonApi + "get_posts/",

    parse: function( response ) {

        return response.posts;

    }

} );

module.exports = PostsCollection;

} );

Issue at hand:

My current challenge involves extending the PostModel by defining

var ImagePostModel = PostModel.extend( { ... } );
and
var GalleryPostModel = PostModel.extend( { ... } );
. The objective is to use the specific model based on the post type (either image or gallery) during data collection. How can I achieve this effectively?

Answer №1

When it comes to backbone properties, rather than directly specifying the object, you have the option to use a function that will return an object. For instance, you can define a function that returns an object for the events hash or the model property.

Rather than explicitly setting a model for your collections using model, you can utilize a function that, based on certain conditions, determines the appropriate model type to use.

As stated in the documentation

A collection can also support polymorphic models by overriding this property with a constructor that returns a model.

Here's an example provided:

var Library = Backbone.Collection.extend({

  model: function(attrs, options) {
    if (condition) {
      return new PublicDocument(attrs, options);
    } else {
      return new PrivateDocument(attrs, options);
    }
  }

});

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

Chaining updateMany() calls in MongoDB while ensuring synchronous response handling

I have encountered an issue while attempting to send 3 separate updateMany requests within a get request, each using a different query. While the first two requests work perfectly, the third updateMany request only functions as expected after refreshing th ...

How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently ret ...

Execute Function on Double-Click with Flot.js

Is there a way to run a function when the mouse double-clicks while using flot? Currently, I am only able to trap the single click with the following code: $(graph).bind('plotclick', function(event, pos, item) { if (item) { .... ...

A tool that showcases outcomes determined by the interaction of two variables

I have two select inputs: <select id="inputA"> <option>1</option> <option>2</option> <option>3</option> </select> <select id="inputB"> <option>1</option> <option>2</opti ...

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

Enhance the app.get response by integrating data fetched from an http.get request

Currently, I am utilizing express and passing the path as a URL parameter. app.get("/download", function (req, res) { var location; var options = { host: 'example.com', port: 80, path: req.query.url.replace(/ /g, ...

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

Extract information from a URL using Regular Expressions

On my page, I have a list of blog post links: <ul class="postlist"> <li><a href="http://someblog.it/blogpost/7/-----.aspx">Post One</a></li> <li><a href="http://someblog.it/blogpost/32/----------.aspx">Post Two< ...

Using Firebase Admin or the regular Firebase with Next.js

Currently, I am working on a project using Next.js and integrating Firebase. I have been successfully fetching data in my components using the Firebase package designed for frontend use. However, I recently attempted to utilize Firebase within getServerS ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

What could be causing the RTCPeerConnection icegatheringstatechange to not function properly?

I have been trying to utilize the icegatheringstatechange event handler, but it doesn't seem to be functioning properly. Is there a different method I can use to monitor changes in icegatheringstate? How can I determine when all ice candidates have be ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

angular 2 text box clearing functionality appears to be malfunctioning

I am currently working on implementing a reusable search box in Angular 2. Although the code is relatively basic, I am new to Angular 2 but have some experience with Angular 1. I am facing an issue where the value is not clearing when the text box is foc ...

Load custom JS with Google

I have integrated the Google Ajax API and now I need to load custom javascript that relies on the libraries loaded by the ajaxapi. What is the best way to accomplish this? ...

Unexpected issue with sliding menu toggle implementation

I have been struggling to make a menu slide to the left when a button is clicked, and then slide back to its original position when the same button is clicked again. Although I have been using the toggle method, it doesn't seem to be working for me. I ...

"Unraveling the depths of a multidimensional array in JavaScript: a comprehensive guide

Seeking assistance from this wonderfully helpful community :) It seems like I might be declaring and creating my arrays incorrectly, as I am trying to add content to an array of arrays but unable to retrieve anything from it. Here's the code snippet ...

Does JavaScript adhere to a particular pattern?

Is there a more streamlined approach to implementing this particular design pattern? function a() { function x() { /* code */ } function y() { /* code */ } /* additional code */ x(); y(); // can be called from here } a(); a.x(); a.y(); I ...

Identify and forward to the mobile-friendly version of the site

I am currently working on a website that requires separate files for mobile view as the html layout poses challenges in making it responsive. My goal is to find code that can detect if the user is accessing the site from a mobile device, and automatically ...

My goal is to utilize React JS to generate a table by sending the values through props using an array of objects

I have experience building tables as part of various projects, but I am facing challenges creating a table based on the provided format for this specific project. My goal is to utilize the RecordTable Component, render the table component, pass the row com ...

Can Google Charts columns be customized with different colors?

Is it possible to modify the colors of both columns in Google's material column chart? Here is the code I am using for options: var options = { chart: { title: 'Event Posting', subtitle: 'Kairos event p ...