Backbone – How to use specific extended model while fetching collection?

I’m trying to create a WordPress theme using Javascript, Requirejs and Backbonejs.

In the index route, I instantiate a new postsCollection app.postsCollection = new Posts.Collection(); which will contain all WordPress posts. Then, I run .fetch() app.postsCollection.fetch( { success: ..., error: ... } );

Read More

Here is the code of 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;

} );

My problem :

I’d like to extend the PostModel defining var ImagePostModel = PostModel.extend( { ... } ); and var GalleryPostModel = PostModel.extend( { ... } );. Then, I’d like to use the specific model while fetching, thanks to the post type (image or gallery) of collected data. How can I do this ?

Related posts

Leave a Reply

1 comment

  1. In general for backbone properties you can instead of specifying the object directly use a function that return an object, for example you can provide a function that returns an object for the events hash. The same is true for the model property.

    Instead of specifying a model for your collections model you can instead use a function that will based on some condition return the appropriate model type.

    From the documentation

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

    And the provided example

    var Library = Backbone.Collection.extend({
    
      model: function(attrs, options) {
        if (condition) {
          return new PublicDocument(attrs, options);
        } else {
          return new PrivateDocument(attrs, options);
        }
      }
    
    });