Note that there are some explanatory texts on larger screens.

plurals
  1. POBackbone.js model with collection
    text
    copied!<p>I have 2 models and one collection. <code>JobSummary</code> is a model, <code>JobSummaryList</code> is a collection of <code>JobSummary</code> items, and then I have a <code>JobSummarySnapshot</code> model that contains a <code>JobSummaryList</code>:</p> <pre><code>JobSummary = Backbone.Model.extend({}); JobSummaryList = Backbone.Collection.extend({ model: JobSummary }); JobSummarySnapshot = Backbone.Model.extend({ url: '/JobSummaryList', defaults: { pageNumber: 1, summaryList: new JobSummaryList() } }); </code></pre> <p>When I call <code>fetch</code> on the <code>JobSummarySnapshot</code> object, it gets everything... Except when I move through the <code>summaryList</code> collection they are all of type <code>object</code> and not <code>JobSummary</code>.</p> <p>I suppose this makes sense since other than the <code>defaults</code> object, it doesn't know that the <code>summaryList</code> should be of type <code>JobSummaryList</code>. I can go through each item and convert it to a <code>JobSummary</code> object, but I was hoping there was a way to do it without having to do it manually. </p> <p>Here's my test code (working <a href="http://jsfiddle.net/vbfischer/NSEVe/" rel="noreferrer">jsfiddle here</a>):</p> <pre><code>var returnData = { pageNumber: 3, summaryList: [ { id: 5, name: 'name1'}, { id: 6, name: 'name2'} ] }; var fakeserver = sinon.fakeServer.create(); fakeserver.respondWith('GET', '/JobSummaryList', [200, { 'Content-Type': 'application/json'}, JSON.stringify(returnData)]); var callback = sinon.spy(); var summarySnapshot = new JobSummarySnapshot(); summarySnapshot.bind('change', callback); summarySnapshot.fetch(); fakeserver.respond(); var theReturnedList = callback.getCall(0).args[0].attributes.summaryList; _.each(theReturnedList, function(item) { console.log('Original Item: '); console.log(item instanceof JobSummary); // IS FALSE var convertedItem = new JobSummary(item); console.log('converted item: '); console.log(convertedItem instanceof JobSummary); // IS TRUE }); </code></pre> <p>UPDATE: It occurred to me that I could override the parse function and set it that way... I have this now:</p> <pre><code>JobSummarySnapshot = Backbone.Model.extend({ url: '/JobSummaryList', defaults: { pageNumber: 1, summaryList: new JobSummaryList() }, parse: function(response) { this.set({pageNumber: response.pageNumber}); var summaryList = new JobSummaryList(); summaryList.add(response.summaryList); this.set({summaryList: summaryList}); } }); </code></pre> <p>This works so far. Leaving the question open in case someone has comment on it....</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload