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: ... } );
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 ?
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
And the provided example