I am trying to implement a simple Backbone app on top of RequireJS, but things aren’t working out. Specifically, I can’t make the Collection to iterate over itself. Below are my model/collection/view extracted from their respective files.
Model:
define([
'backbone'
], function(Backbone) {
'use strict';
var m_Song = Backbone.Model.extend({
});
return m_Song;
});
Collection:
define([
'backbone',
'../models/model'
], function(Backbone, m_Song) {
'use strict';
var c_Songs = Backbone.Collection.extend({
model: m_Song,
url: './path/to/JSON.json',
initialize: function() {
this.fetch();
}
});
return new c_Songs();
});
View:
define([
'jquery',
'underscore',
'backbone',
'../collections/collection'
], function($, _, Backbone, c_Songs) {
'use strict';
var v_Main = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var $_html = (function(){
var $_res = [];
console.log(c_Songs);
c_Songs.each(function($_v, $_k) {
/* =====================> Codes in here won't run <===================== */
});
_.each(c_Songs, function($_v, $_k) {
/* =====================> Won't run either <===================== */
});
return $_res;
})();
return this.$('tbody').append($_html);
}
});
Am I doing anything wrong? For the record, below is the output of console.log(c_Songs);:
─ d
├─ _byCid
├─ _byId
├─ length
└─ models
├─ length
└─ 0
├─ _callbacks
├─ _escapedAttributes
├─ _pending
├─ _previousAttributes
├─ _silent
├─ attributes
└─ (My JSON response can be found here!)
├─ changed
├─ cid
└─ collection
But I am convinced I should not access my JSON data in such a weird way like c_Songs.models[0].attributes; there must be something wrong.
How should I do it right to get the Collection iterate over itself?
Found the perfect solution here thanks to mu!