I have a backbone model variable called companies with an object array type. By putting it to the console I get this:
This object is loaded with the fetch function:
require(["collections/Companies"],
function(Companies) {
var companies = new Companies();
companies.fetch();
console.log(companies[0].get("name"));
});
companies.js:
define([
'models/Company'
], function(CompanyModel) {
'use strict';
var CompanyCollection = Backbone.Collection.extend({
model: CompanyModel,
url: 'scripts/data/companies.json'
});
return CompanyCollection;
});
company.js:
define([], function () {
'use strict';
var CompanyModel = Backbone.Model.extend({
defaults: {
id: '',
name: '',
description: ''
}
});
return CompanyModel;
});
I have tried to get the attributes by using get according to the tutorials (console.log(companies[0].get("name"));
) with no luck.
What is the correct syntax to get the attributes?
Thanks in advance
To get model from collection you can use Backbone collection method - collection.at(INDEX);
Example code:
var collection = new Backbone.Collection();
collection.add({ id: 1, name: "S"});
collection.add({ id: 2, name: "F"});
console.log(collection.at(0).attributes); // { id: 1, name: "S"}
var model = collection.at(0);
// get attributes from model
console.log(model.get("name")); // "S"
You can play with demo
To get models from collection use : collection.models (you will get array of models)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments