adding multiple model objects to a backbone collection - backbone.js

I am trying to add a couple of models to the collection
rolesSuccess: function(roles) {
var role1 = new Role({
id: "1",
Name:"TST1",
Description:"Test 1"
});
var role2 = new Role({
id: "2",
Name:"TST2",
Description:"Test 2"
});
roles = new Roles();
roles.add(role1);
roles.add(role2);
this._context.roles(roles);
}
I only see one role being added at any point, just the first one. What am I doing wrong?

you can pass an array of models to a backbone collection when you initialize it.
var roles = new Roles([role1, role2]);

Related

Accessing values from a Map<string, List<string>>

I'm struggling to get the string values from a Map<string, List<string>> object. The object contains this information:
{"thisKeyName": [Array]}
The [Array] contains something like this:
["Contact 1", "Contact 2", "Contact 3"]
I'm able to access the [Array] values of the object like this:
let contactCards = currentUser.contacts; // <- this is the Map object
const ids = [];
contactCards.forEach(folder => {
folder.forEach(contact => {
ids.push(contacts);
});
});
However, I want to access the "ThisKeyName" value to put it on another array. How can I achieve this?

adding new object inside of array of objects in react

I am having a little problem when trying to add a new object to an array of objects which is stored in state.
Below is a example of the object which is stored in state (scratchTickers):
id : uuid.v1(),
area : 'Scratch',
name : 'Untitled',
status : "",
size : "",
created : {
name : "username",
time : new Date()
},
modified : {
name : "username",
time : new Date()
},
content: [{
content: "Dummy content",
TowerRed: "",
TowerText: "Headlines"
}]
I need to dynamically add new objects in the content array, an object is structured like this:
{
content: "Dummy content",
TowerRed: "",
TowerText: "Headlines"
}
I am trying to use React's immutability helpers to accomplish this but It doesn't seem to be working as it should.
here is my function to add a new object to the content array and update the state:
_createTickerItem: function (id) {
var tickerID = id;
var key = null;
for (var i = 0; i < this.state.scratchTickers.length; i++) {
if(this.state.scratchTickers[i].id == tickerID) {
var ticker = this.state.scratchTickers[i];
var key = i;
}
}
var blankContent = ({
content: "Ticker Content",
TowerRed: "",
TowerText: "Headlines"
});
var oldContent = this.state.scratchTickers[key];
var newContent = update(oldContent, {
content : {
$push : [blankContent]
}
});
this.setState({
scratchTickers: newContent
});
},
So when i clicl the button tun run the _createTickerItem function the component re-renders and the main object has disappeared entirely.
Edit* Ok so I am now 1 step further making sure to set 'newContent' as an array during set state now adds new objects to the content array and renders them correctly.
this.setState({
scratchTickers: [newContent]
});
However if there were multiple objects in state, this will replace them all with juts a single object. So how would it work if I had say to parent objects in state but wanted to just modify the content array of object 1?
Edit 2: i should add that scratchTickers is an array of objects, so the for loop is needed to make sure i modify the correct object.
You're replacing the entire scratchTickers array with only the last updated object.
You have to update the entire array first.
var updates = {};
updates[key] = { $set: newContent }
var newScratchTickers = update(this.state.scratchTickers, updates);
this.setState({
scratchTickers: newScratchTickers
});

How to search array of object in backbone js

how to search array of object in backbone js.The collection contain persons model.
[{
name: "John",
age: "18",
likes: {
food: "pizza",
drinks: "something",
}
},
......
]
how can i get persons who likes something.
i did try collection.where({likes :{food : "pizza"}});
Since your food property is in an object on the Person's attributes, using where (which by default just looks at the flat attributes) isn't going to work. You can use the filter method to apply a truth test to all of the items in your collection and just get the ones that pass.
In the code you posted, it doesn't look like you have a Backbone Collection proper, just a regular array of objects.
Since Underscore is on the page, you can use it to help filter through your list.
var people = [
{
name: "John",
age: "18",
likes: {
food: "pizza",
drinks: "something",
}
},
......
];
var likesPizza = _.filter(people, function(person) {
return person.likes.food === "pizza";
});
If it is in fact a Backbone Collection, you can use
this.collection.filter(people, function(person) {
return person.get('likes').food === "pizza";
});

Getting models in nested collections in Backbonejs

I'm working in a collection that contains a model with collections of "itself". For example:
[{
id: 1
name: "John",
children: [
{
id: 32
name: "Peter",
children: []
},
{
id: 54
name: "Mary",
children: [
{
id:12,
name: "Kevin"
}
]
},
]
}]
Let say that I want to get the Kevin "user" by its Id. But all that I have is the "first collection". How can I do that?? And about setting a user within a collection? Another thing: Its possible to get all the Kevin "parents" from him? Like Mary and John?
Does anyone has come to a issue like that?
Thanks a LOT
Well I've made a recursive function on the User's Collection that seems to solved the problem for now ( the best of this is that I can use for retrieve a "deep" model and change it.). Something like that ( if someone has any suggestions, be free to give it a opinion ):
findUserById: function(id) {
var self = new Backbone.Collection(this.toJSON());
return thisCollection(id, this);
function thisCollection(id, collection, array) {
var innerSelf = collection || this;
var thisArray = array || [];
for(var i = innerSelf.models.length; i--;) {
if(innerSelf.models[i].get('id') == id) {
return [innerSelf.models[i]].concat([thisArray]);
}else {
if(innerSelf.models[i].get('children').length > 0) {
thisArray.push(innerSelf.models[i]);
return thisCollection(id, innerSelf.models[i].get('children'), thisArray);
}else {
innerSelf.remove(innerSelf.models[i]);
return thisCollection(id, self, []);
}
}
}
}
}
Basically I return an array with 2 items. The first is the record that I'm looking for and the second is an array with the parents of this user.
Underscore (which is a Backbone dependency, so you already have it) is great for this sort of thing; if you use its "map" function (which Backbone provides as a method on Collection) with its find function, you can do the following:
findPersonInPeopleCollection: function(nameWeAreLookingFor) {
function findChildren(person) {
if (!person.children) return [person];
var children = _.map(person.children, function(child) {
foundPeople.push(findChildren(child);
})
return _.flatten(children);
}
var allPeople = _.flatten(myCollectionOfPeople.map(findChildren));
return _(allPeople).find(function(person) {
return person.get('name') == nameWeAreLookingFor;
}
}
If you wanted to store the parents initially you could either add logic to your "Person" model class's initialize function, eg.
var Person = Backbone.Model.extend({
initialize: function() {
_.each(this.get('children'), function(child) {
child.parent = this;
}, this);
}
});
You could also do something similar by overriding your collection's add method, or adding an event handler to it that triggers after people get added.

Backbone relation model and collection.length

Let's suppose I have the following model (model1) and collection (collection1)
model1.attributes = {
name: 'bar'
};
collection1.models = [{}, {}, {}];
It will be possible by using backbone relation to make the model1 to know about the length of collection1?
model1.attributes = {
name: 'bar',
collection1Length = 3 // collection1.models.length
}
Thanks
Based on your comments, it might be best to simply create a reference to the collection itself within the model:
ModelName = Backbone.Model.extend({
...
linked_collection: null // don't call this 'collection', as model.collection already exists
...
}
var model1 = new ModelName();
model1.set('linked_collection',collection1);
Now you can do this at any time to get the linked collection's length.
model1.get('linked_collection').length

Resources