Automatically create subclasses and reclassify object lists with CanJS

My CanJS script receives a list of results from a remote JSONP server in this format:

[
    { "class": "ABaseClass", "value": "1"},
    { "class": "ASubClass", "value": "2"},
    { "class": "ABaseClass", "value": "3"},
    { "class": "ASubClass", "value": "4"}, 
    ...
]

Type refers to the object's class, defined in CanJS using can.Model.extend:

The example code below shows how CanJS is set up:

ABaseClass = can.Model.extend({ ... }, {
    'findAll': { 'url': 'the url', 'dataType': "jsonp" }
});

// ASubClass is a subclass of ABaseClass.
ASubClass = ABaseClass.extend({ ... }, { ... });

Issue:

When

ABaseClass.findAll({}, function(data) { ... })
makes a call to the JSONP endpoint for more objects, the callback only retrieves models of class ABaseClass.

Query:

Does CanJS offer a method to automatically create subclasses based on a field within a list of objects? If not, how can I implement one?


Desired result:

[
    (new ABaseClass(...)),
    (new ASubClass(...)),
    (new ABaseClass(...)),
    (new ASubClass(...)),
    ...
]

Environment details:

  • CanJS: 1.17
  • jQuery: 1.10.1
  • I do not have control over the types of objects returned by the endpoint.
  • Multiple AJAX calls are not an acceptable solution.

Answer №1

To easily achieve this, one can override the models method and identify the correct model for the class in the following manner:

ABaseClass = can.Model.extend('ABaseClass', {
    'findAll': { url: "/the_url", dataType: "jsonp" },
    models: function(results){
        return_models = new can.List();
        can.each(results, function(result){
            return_models.push( window[result.class].model(result.value) )
        })
        return return_models;
    }
}, {});

ASubClass = ABaseClass.extend('ASubClass', {}, {});

ABaseClass.findAll({}, function(results){
    console.log(results);
})

This process works as follows:

  1. Upon the completion of findAll, the result is sent to the models method.
  2. The models method iterates over each result.
  3. It then locates the model constructor attached to the window ( window[result.class] ).
  4. Next, the model function is called on the constructor to create/update the model instance.
  5. The model instance is added to a can.List and returned.

Testing has been performed on CanJS 2.0.x, where it functions correctly.

Further information on how this operates can be found in the documentation:

However, it appears that these methods will be deprecated in CanJS 2.1.0 in favor of .parseModels and .parseModel.

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

Invoke a function from a different vue.js component using the this.$refs property

I'm facing an issue with triggering a sibling element. What I've tried so far <b-img @click="callFileLoader"/> <b-file type="file" ref="fileUploader"></b-file> ... methods:{ callFileLoader () { this.$refs.fileUploader.c ...

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed https://i.sstatic.net/YkHp0.png I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.d ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

Leveraging Angular CLI in conjunction with the newest AspNetCore Angular 4 Single Page Application template

I'm currently experimenting with using Angular CLI alongside the latest JavaScriptServices AspNetCore Angular Spa template. In the past, I would simply copy and paste a .angular-cli.json file into my project's root directory, change "root" to "C ...

When using JavaScript, an error may occur that says "Cannot read property 'style' of null," but strangely, this issue disappears when the code is copied and

I seem to be encountering an error in my codepen and I can't figure out what I'm doing wrong. It appears that I may have misplaced something, but I would greatly appreciate any help or explanation of my mistake. function on() { document ...

When you hover your cursor over specific keywords, they will light up and glow in the sentence or paragraph

Looking to create a sentence or paragraph like "I enjoy taking my dog for a walk." with categories such as "Nouns", "Verbs", etc. I envision the ability for users to hover over "Nouns" and have words like "dog" and "walk" light up, while hovering over "Ver ...

Ensure Rxjs waits for the completion of the previous interval request before moving forward

Scenario: It is required to make an API call every 3 minutes to update the status of a specific service within the application. Here is my existing code snippet: interval(180000) .subscribe(() => this.doRequest ...

Ways to properly update a state variable when using onClick within a functional component

I'm having an issue with my tabs that are supposed to display different products and filters when clicked. Currently, I have to click each tab twice before the 'options' list updates with the correct filters. I know that calling setOptions w ...

Navigating to the bottom of a page once an element is displayed (with react-slidedown)

I'm facing a bit of a challenge here that I haven't been able to resolve yet. So, I have this optin form that is revealed upon clicking on a link. The reveal effect is achieved using react-slidedown. The issue I'm encountering is that when ...

Change the format into a PHP array

In my workplace, I am confronted with a frustrating system that generates the following output: { party:"bases", number:"1", id:"xx_3039366", url:"systen01-ny.com", target:"_self", address:"Ch\u00e3o as Alminhas-Medas,Uteiros ...

Stop the React timer count for a moment

I am currently attempting to implement a pause feature in a countdown timer using React. Here is the code snippet: export default function Home() { const timerRef = useRef(180) const [minute, setMinute] = useState(3) const [second, setSecond] = useS ...

Why is PHP unable to locate the index sent in the JSON data?

Why can't PHP seem to locate my index, myPostData? Utilizing jQuery/AJAX $('a').on("click", function(){ $.ajax({ type: "POST", url: "../image_view.php", data: {myPostData : {"lastName":"Sperrow", "firstName":"J ...

Troubleshooting Problem with Retrieving Files Using jQuery Ajax

I am attempting to use ajax to retrieve the contents of a file, but it doesn't seem to be functioning properly. I'm not sure why this is happening, as I have copied the same code from the examples on w3schools.com. $().ready(function(){ ...

PHP project encountered an error stating: "Uncaught TypeError: Ajax is not a function"

I am in the process of configuring an apache server for a project using XAMPP, MySQL, and PHP 5.6 Unfortunately, it appears that there is an issue with how JavaScript has been referenced in the project, and I am unable to get it to function correctly (th ...

Error: The JSON input unexpectedly ended, however the PHP file itself is error-free

When trying to display data retrieved using PHP through JSON/Ajax, I encountered an error message: [object Object] | parsererror | SyntaxError: Unexpected end of JSON input The PHP script is functional (I can view the JSON output by directly accessing th ...

Encountering issues when attempting to retrieve localized images within .vue files using a custom webpack configuration

Currently, I am deep into learning webpack and attempting to craft my own vue template. However, I have encountered an issue that does not arise in webpack-simple or other templates. Despite having a configuration for images that closely resembles what is ...

Update the JSON object and store the changes

I have a json array object that requires modification and saving the updated version to a variable. The original json object is: var json = [ { "Name": "March-2016", "Elements": [ { "Name": "aa", "Elements": [ { ...

The issue with Bootstrap 4 modal not closing persists when loading content using the .load() function

Having an issue with my Bootstrap 4 modal, as I'm loading the body content externally using .load(), but it's not closing when I click on the close buttons. Any help would be highly welcomed. JavaScript Code Used: if(status){ $('#cartMe ...

Unusual feedback received from the .NET server following an Ajax call

As I delve into the world of ASP .net, I decided to move past the traditional 'hello world' and explore some basic backend request handling. My approach involved making an Ajax request from my webpage to the ASP page: Ext.Ajax.request({ ...

Using JavaScript to dynamically set a background image without the need for manual hard-coding

My attempt was to showcase images as a background image upon mouseover event for the div section with id 'message' by manually coding JavaScript functions for each image like this: Here is the HTML code inside the body section <div id = "mes ...