backbone.js,collections,fetch , Backbone.js collection fetch not setting response objects as models

Backbone.js collection fetch not setting response objects as models


Tag: backbone.js,collections,fetch

When fetching a collection, my api response has 10 objects, but the resulting Backbone collection only has 1 model with an attributes array containing the 10 response put it another way, the fetch is not creating models out of the objects in my response...and I don't know why.

Model definition:

MyApp.Item = Backbone.Model.extend({
    initialize: function(){


Collection definition:

MyApp.ItemCollection = Backbone.Collection.extend({
    model: MyApp.Item,
    url: '/api/v1/item/',
    parse : function(response){
        //api returns objects in the content attribute of response, need to override parse
        return response.content;  

Calling fetch:

var myCollection = new MyApp.ItemCollection();

    traditional: true,
    data: {  //url params for api call
        order: 'sort_date:desc',
        start: 0,
        num_items: 10,



4571221007823F95BAAFB2BDF81111XX: Object
0124207763051005AAF59694458EBFXX: Object
3324207755431003B589CEF237DBE1XX: Object
3470000061641005BFB5D9983156E0XX: Object
3515553061641005A02884677F5624XX: Object
3526033426761006AFEA9852B0DDB5XX: Object
21431252714010079E4D8413429DB0XX: Object
26570547220410068F60D1B07D2E08XX: Object
37557124663710079DDC81EE855981XX: Object
0152243312031007957B94F5073B69XX: Object

//api successfully returns an array of objects, with GUID as key


r {length: 1, models: Array[1], _byId: Object}

//why only one model? why not 10?


4571221007823F95BAAFB2BDF81111XX: Object
0124207763051005AAF59694458EBFXX: Object
3324207755431003B589CEF237DBE1XX: Object
3470000061641005BFB5D9983156E0XX: Object
3515553061641005A02884677F5624XX: Object
3526033426761006AFEA9852B0DDB5XX: Object
21431252714010079E4D8413429DB0XX: Object
26570547220410068F60D1B07D2E08XX: Object
37557124663710079DDC81EE855981XX: Object
0152243312031007957B94F5073B69XX: Object
__proto__: Object

//there they are...but why?  

How can I change the fetch to get these objects added as individual models in myCollection?


The response must be an array. Each item in the array is turned into a model. Your response is an object.

Update your parse method to pull out the values (as an array) from the response into an array and it'll work.

MyApp.ItemCollection = Backbone.Collection.extend({
    model: MyApp.Item,
    url: '/api/v1/item/',
    parse : function(response){
        //api returns objects in the content attribute of response, need to override parse
        return, function(model, id) {
   = id;
            return model;


What is the best way to iterate two hashmap in same loop in java?

What's the best way to iterate over the below two maps together? I want to compare two maps values which are strings and have to get the keys and values. HashMap<String, String> map1; HashMap<String, String> map2; ...

Java Generic Map with Generic Type as key/ values

I want to write a method which takes a Map as an parameter, which can contain any object as its value. I am trying to implement it using generics, but I am unable to implement it. Below is the code that I have tried so far. This code as two...

Backbone render template in side el's nested id

I have my html setup like this. <div id="product-module"> <ul id="product"> <li><input name="product" type="radio"/></li> <li><input name="product" type="radio"/></li> <li><input name="product" type="radio"/></li> </ul> <table id="quantities"/> <script id="myTemplate" type="text/x-handlebars-template"> {{#each this}} <tr> <td class="quantity"> <label class="checked" for="quantity_{{id}}"> <input type="radio" value=""...

Iterator for an array list of Class

Am New to Java so please bear with me if my question seems to be silly. I am learning collections,I have written a program which will store student names id and marks.I am storing all these in a Arraylist. Using for loop I am able to print the values in...

Entity Framework, Code First, Update independent association (Collection)

to explain the problem I have a simple model with a class Person: public class Person { public int Id { get; set; } public virtual string Name { get; set; } } and a class School with a collection of Persons: public class School { public int Id {...

Handlebars: return hash from helper

Can i return hash from Handlebars helper? I tried this: In my view: initialize: -> super this.hash = {key1: 'test1', key2: 'test2'} Handlebars.registerHelper 'show', => return this.hash In template: {{show.key1}} What am i doing wrong? Thanks!...

Backbone this.el is undefined

I've been following along to the a tutorial i found on youtube. In the tutorial I don't see him defining el : ... but he's calling this.$el and it appears to be working. In jsfiddle, I have been following along, but get a js error saying Backone this.el is...

“Segmentize” collection with lodash

I have a collection col1 var col1 = [1, 8, 9, 10, 2, 54, 7]; I have another collection col2 var col2 = [1, 8, 23, 9, 46, 10, 2, 54, 78, 7] ...that I know it contains every element of col1, plus some other elements I want to...

add subitems to meteor document

I have a meteor collection "list" that has the following data structure. "list" : [ { "_id" : "id", "author" : "authorId", "createdOn" : "DateTime", "description" : "description", "items" : [ { "item1" : { "itemComplete" : "Boolean", "itemName" : "item name", "itemDescription" : "item description", } }, { "item2"...

joining two collections in C# or JavaScript

I have two objects of "pseudotype" Hash(int key, list values) that I need to combine into one based on the key. For example, [{1, {a, b, c}}, {2, {apple, pear}}, {3, {blue, red}}] and [{2, {tomato}}, {3, {pink, red}}, {4, {x, y, z}}] The result that I need is: [{1,...

Underscore templates with Backbone

I'm completely new in backbone framework. I have a model itemsOnSaleModel that contains an array of items and a View itemListView that render these items. The problem is that I can't figure out how to write the template correctly. Usually in this case I would have written something like this:...

Java generic usage error

The code below uses simple generics and compiles correctly. When I try to create a object of type McDelayQueue, I get an error. public class McDelayQueue<E extends Delayed & IValue<K>, K> extends DelayQueue<E> { final Set keys = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>()); @Override public E take() throws InterruptedException { E data...

Backbone.js collection fetch not setting response objects as models

When fetching a collection, my api response has 10 objects, but the resulting Backbone collection only has 1 model with an attributes array containing the 10 response put it another way, the fetch is not creating models out of the objects in my response...and I don't know why. Model...

Merge two object arrays for Chart

I've two arrays which I'm going to merge and then load in chart. range = date array generated from moment.js, there is date of every day in example one month or specific date range with one another attribute count: "0" data = fetched data from database through backbone Now I...

Why `init` of shim in my require.js configuration not called?

Update: I was writing a small module to handle this csrf token problem in backbone until I got push notification of @Louis's answer. His answer is quite elegant and seems nice, but I'll leave a link to my backbone.csrf module github repo just for anyone who needs it. ==================================================================== I'm...

Mapping a list to Map Java 8 stream and groupingBy

I have this simple Bean class: public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } In...

Backbone.js remove model from collection

I'm learning Backbone and for the life of me I can't remove a model from a collection. The collection 'remove' event fires, but the collection appears to remain the same. Here's what I have so far:,output I remove the model from the collection upon click. Then, the list view...

Using counter on array for one value while keeping index of other values

After reading the answers on this question How to count the frequency of the elements in a list? I was wondering how to count the frequency of something, and at the same time retreive some extra information, through something like an index. For example a = ['fruit','Item#001'] b = ['fruit','Item#002']...

VBA Debugger shows only 256 elements of a collection

the title explains my problem. Im working on an excelmakro and my questions is, is there an option that the debugger shows all elements like it does with an array? And if not, is the only workaround the storage of my classobjects in an array after inflating the collection? I...

How to convert single element list to java 8 optional

How to nicely convert list containing one or zero elements to Optional? The ugly code: List<Integer> integers = new ArrayList<>(); Optional<Integer> optional = integers.size() == 0 ? Optional.empty() : Optional.of(integers.get(0)); ...

CollectionView - collection data not being passed to childView

I'm trying to make the collectionView work , but I'm not really sure whether the CollectionView initiates the fetch method automatically and then populates the ChildViews with the fetched data. Or is it something I need to do manually? I have checked the Marionette doc page but I couldn't find...

Loop by Object inside another Object in Java

I'm not sure how to ask this in word so here's an example : Building class have a data like this : Map<Season, List<Info>> infosBySeason = new TreeMap<Season, List<Info>>(); What I'd like to do is loop for each Building, print by Season infos. Like : Season 1 : Building 1...

Java - Create sublist from a list based on suffix

I'm trying to create sublists from a list based on the suffix. public class Test { public static void main(String args[]) { List<List<String>> subList = new ArrayList<List<String>>(); List<String> myList = new ArrayList<String>(); myList.add("Text_1"); myList.add("XYZ_3"); myList.add("ABC_1"); myList.add("Text_2"); myList.add("Text_3"); myList.add("XYZ_1"); myList.add("XYZ_2"); myList.add("ABC_2"); for (String item : myList) { List<String> tempList = new...

LoDash - DeepFlatten array of objects

I have the following collection. Each object may have a children array of objects, which may have a children array of objects and so on... [ { "name": "John", "age": 24, "children": [ { "name": "Jack", "age": 53, "children": [ { "name": "Jenny", "age": 88 } ] } ] },...

Marionette - listenTo a custom event triggered from a collection

I'm using a Event Aggregator(EA) to keep track of all events in my app. But there is one situation I could not make the EA listen to a custom event triggered from a collection. See more details below. eMgr (Event Manager i.e Event aggregator): define(['backbone.wreqr'],function(Wreqr){ "use strict"; return new Wreqr.EventAggregator();...

Persisting data client side for event driven approach

I have an application that renders activities and looks like this: The map should render markers based on some criteria (date_start, date_end, map_bounds). Activities are loaded from a REST api with ajax. The front end approach is event driven (using Backbone / Marionette); activities are dynamically udpated when the date...

Add two events in backbone.js

I added two jQuery events, the second jQuery event is not triggering. What might be the issue? Here is my code : var ListView = Backbone.View.extend({ events: function() { $('#couponcheck2').click(function(e) { e.preventDefault(); $('#couponcheck').empty(); $('#couponcheck').append('<div class="col-xs-8"><input type="text" class="form-control" id="enterCoupon"></div>'); $('#couponcheck').append('<div class="col-xs-8"><button type="button" class="btn btn-success btn-sm" id="couponbutton"><span...

Backbone.js - Model's attribute is not getting passed to view correctly

I am very new to backbone and trying to understand why "title" is not getting passed to view and printing correctly. If I create model with title properties it passes to view and prints fine. Any pointer will be greatly appreciated. HTML: $(document).ready(function(){ //Model var Appointment = Backbone.Model.extend({ urlRoot :...

Merge multiple lists based on List priority

I have couple of lists where each list has different priority. When i merge these lists i should get with height priority on top. Assume i have 3 lists and different objects value common in 3 lists should come first and then the top priority list should be appended vice...

Why doesn't my sample throw ConcurrentModificationException [duplicate]

This question already has an answer here: Why isn't this code causing a ConcurrentModificationException? 4 answers I wrote this example following a test ConcurrentModificationException concept: public class Person { String name; public Person(String name) { = name; } } public static void main(String[] args) { List<Person> l =...

Merge two or more T in List based on condition

I have the below class: public class FactoryOrder { public string Text { get; set; } public int OrderNo { get; set; } } and collection holding the list of FactoryOrders List<FactoryOrder>() here is the sample data FactoryOrder("Apple",20) FactoryOrder("Orange",21) FactoryOrder("WaterMelon",42) FactoryOrder("JackFruit",51) FactoryOrder("Grapes",71) FactoryOrder("mango",72) FactoryOrder("Cherry",73) My requirement is to merge the...

Backbone's success callback called before jquery's ajaxSuccess

I would like to make sure that jQuery's ajaxSuccess callback is called before Backbone's success, which is not the case in my experience. I would like this someModel.fetch({ success: function() { console.log('2'); } }); $(document).ajaxSuccess(function(event, xhr, ajaxOptions) { console.log('1'); }); to log 1, 2 and not 2, 1. The reason...

Extend Coffeescript subclass function from parent in marionette

I've got a "FormView" class in my Marionette application that sets up a lot of things for form submissions around my app. I use it every time there is a form. I've also got some helpers that I want to pass into every form template via the templateHelpers method, but...

Marionette CompositeView - change in template each nth items

I'm using Marionette for a while, but I'm not sure how I can do what I want, in a simple manner. I have a composite view, which renders something like this: <div class="row"> <div class="col-xs-12"> <div id="items"></div> </div> </div> Each of my item is being rendered as a: <div class="col-xs-3">foo</div>...

getting a value from a map in java with index

The item shown below is the result obtained from debugging a map {0={PRODUCT_TYPE.PRODUCT_AMT=200}} To store this value in a string I have used this code String amountCheck=(String) productsFieldMap.get("PRODUCT_TYPE.PRODUCT_AMT"); However this does not seems to work. Can anyone suggest me a way to do this? The productsFieldMap represents the map where...

backbone stickit - reverting model changes

I'm now testing backbone stickit for two-way data binding. Is there a way to revert the changes, for example, while editing a model data through a form, the user press the cancel button, as in the pic below It seems the model was changed on the fly as we type...

Search for key in Map when the values are in ArrayList [closed]

I am new to the collections in Java , I have a HashMap<String, List<String>>. I want to search for a key from the Map when a value is given. The map stores the data of a state as key and its cities as the list. So it is assumed that...

PLSQL move data from csv list stored in varchar2 to a collection of integers

Oracle Express 11G R2: In PLSQL I have a varchar2 containing a CSV list of values like this: vList:='1212,3232,3232,4343,54545,65654,65665,65654,788787' I would like to move these into a collection, so i create a new type: CREATE TYPE INTEGER_TT AS TABLE OF INTEGER; then declare my variable: my_list INTEGER_TT; What is the...

What is the use of HTML5 pushState in Backbone History Start method

I have a simple Backbone app. I am trying to understand the difference created by passing pusState: true when starting Backbone.History object. JavaScript var r = new (Backbone.Router.extend({ routes: { "users": "allUsers", "users/new": "createUser" }, allUsers: function () { v.render("showing all users"); }, createUser: function () { v.render("showing form for...

CSS Selector Equivalent Of jQuery.find in backbone.js?

I have a Marionette view that has the following code: onRender: { $('#someDiv').find('a').click(function(){ // some code here }); } But I want to refactor to something like this: events: { 'click [selector here]': 'executeCode' }, executeCode: function() { // some code here } Is this possible?...

Can't call fetch directly in Backbone model listenTo

I'm trying to have a model listen to a collection and fetch itself when the collection changes: class Team extends Backbone.Model urlRoot: '/team', initialize: function(attributes, options) { this.listenTo(members, 'change', this.fetch) The fetch does seem to trigger, but the url is all messed up, and to get it to work I...

Backbone datatypes - type casting?

It just took me over an hour to find out that a Backbone query on a collection was failing because I queried the wrong data type. So this query failed because I used the wrong data type for id: element = collection.findWhere({id: "123", att: true}); This one worked and returned...

What is the correct way to override Marionette compositeview render

I am showing a table view using Marionette's composite view. The composite view's template has a tbody with an initial which shows a loadding animation gif. Now, when the render method is called, I want to remove this initial row and then append the results of collection fetch. However the...

Where to format collections / objects

From front end architectural point of view, what is the most common way to store scripts that perform transformations on collections of objects/models? In what folder would you store it, and what would you name the file / function? Currently I have models, views, controllers, repositories, presenters, components and services....

Dropzone.js status is pending and not uploading a file

I am using Multer in back-end to handle file upload and Dropzone.js in front-end. Everything is fine when I use Postman to test my back-end code, but in when I use Dropzone the status is pending and file not getting uploaded. Then after 4 minutes of waiting I get Timeout...

why java API prevents us to call add and remove together?

As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

Comparison Express JS, Angular JS vs Backbone JS [closed]

I am starting to learn node js for a while and it seem amazing. When I start to apply nodejs to build a scalable website, I am wondering to do Express for back-end, BackBone Js or Angular JS for front-end, people said Express JS is very fast, while Backbone.js seem...

Returning an Iterator from String[] [duplicate]

This question already has an answer here: Iterator of Object[] 2 answers I have a class foo with a field String[] bar. I want foo to implement Iterable<String>. So I'm writing @Override public Iterator<String> iterator() { // ToDo - return some function of `bar` } What can I put...

passing backbone collection to view

I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work. I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will...