Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing Models in Backbone Collection
    text
    copied!<p>I am struggling to access the models in my collection despite reading all kinds of solutions to this issue and trying them out - there is obviously something I am not getting - PLEASE HELP!</p> <p>I have a collection where the data comes from an XML file as follows:</p> <pre><code>define([ 'underscore', 'backbone', 'localstorage', 'models/script/ScriptModel' ], function(_, Backbone, LocalStorage, ScriptModel) { var ScriptsCollection = Backbone.Collection.extend({ model : ScriptModel, url: '/data/script.xml', parse: function (data) { var parsed = []; $(data).find('play').each(function (index) { var title = $(this).find('title').text(); var author = $(this).find('author').text(); parsed.push({ title: title, author: author }); }); return parsed; }, fetch: function (options) { options = options || {}; options.dataType = "xml"; return Backbone.Collection.prototype.fetch.call(this, options); } }); return ScriptsCollection; }); </code></pre> <p>This all seems to be working okay, then in my view I do the following:</p> <pre><code>define([ 'jquery', 'underscore', 'backbone', 'views/settings/SettingsView', 'models/script/ScriptModel', 'collections/scripts/ScriptsCollection', 'text!templates/script/scriptTemplate.html' ], function($, _, Backbone, SettingsView, ScriptModel, ScriptsCollection, scriptTemplate) { var ScriptView = Backbone.View.extend({ el : $("#container"), initialize: function(){ this.collection = new ScriptsCollection(); this.collection.fetch(); }, render : function() { this.$el.html(scriptTemplate); //add the settings view var settingsView = new SettingsView(); settingsView.render(); } }); return ScriptView; }); </code></pre> <p>Now if I console log 'this.collection' I can see:</p> <pre><code>child {length: 0, models: Array[0], _byId: Object, constructor: function, model: function…} _byId: Object length: 1 models: Array[1] 0: child _changing: false _events: Object _pending: false _previousAttributes: Object attributes: Object author: "Eric and Ernie" title: "The Play Wot I Wrote" __proto__: Object changed: Object cid: "c3" collection: child __proto__: Surrogate length: 1 __proto__: Array[0] __proto__: Surrogate </code></pre> <p>where in 'models' I can see my data in 'attributes' but if I log 'this.collection.models' I see an empty array. I can also see that the length of models is 0 so I am confused by this??</p> <p>I just can't seem to figure out why this is the case though my guess is I am just missing something fundamental here?? - Backbone noob I'm afraid!</p> <p>Any ideas........anyone??</p> <p>Thanks in advance</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