VueJs How to duplicate object from v-repeat? - javascript

Functionality allows you to add/delete description, title and time for the event.
I can not deal with the duplication(cloning) of the object which is created through v-model = (event.name, event.description and event.date)
All works fine with the removing selected object, it works like this:
deleteEvent: function(index){
if(confirm('Are you sure?')) {
this.events.$remove(index);
}
}
Here's an example of my code for a application to adding and changing events.
var vm = new Vue({
el: '#events',
data:{
event: { name:'', description:'', date:'' },
events: []
},
ready: function(){
this.fetchEvents();
},
methods: {
fetchEvents: function() {
var events = [
{
id: 1,
name: 'TIFF',
description: 'Toronto International Film Festival',
date: '2015-09-10'
},
{
id: 2,
name: 'The Martian Premiere',
description: 'The Martian comes to theatres.',
date: '2015-10-02'
},
{
id: 3,
name: 'SXSW',
description: 'Music, film and interactive festival in Austin, TX.',
date: '2016-03-11'
}
];
this.$set('events', events);
},
addEvent: function() {
if(this.event.name) {
this.events.push(this.event);
this.event = { name: '', description: '', date: '' };
}
},
deleteEvent($index)"
deleteEvent: function(index){
if(confirm('Вы точно хотите удалить данную запись?')) {
this.events.$%remove(index);
}
},
cloneItem: function(index) {
}
}
});
there full code
http://codepen.io/Monocle/pen/ojLYGx

I found undocumented built it extend function Vue.util.extend that is equivalent to jQuery's extend.
In this case, you can avoid the enumerating the object properties
cloneItem: function(index) {
this.events.push(Vue.util.extend({},this.events[index]));
}

Access the cloned object via this.events[index], and then use it's properties to create new object and push it into events array:
cloneItem: function(index) {
this.events.push({ name: this.events[index].name,
description: this.events[index].description,
date: this.events[index].date });
}
Demo: http://codepen.io/anon/pen/MajKZO

Related

What does this 'child' in my javascript array mean?

I keep getting these 'child' things in my Javascript collection after certain operations. The 'child' keyword is showing up in my terminal after logging the Javascript collection.
Whats strange is that I can't actually find good documentation anywhere online on what this means. Seems like it should be a basic concept.
When I do google it I just get a ton of results for 'child' in context of HTML and the DOM.
What does it mean in javascript? And how could I fix this collection to have these nested collections without the 'child' thing.
Gosh I wish I could speak about it with more sophistication :p
More Context on How This 'Bad' Collection is Generated
So I'm trying to populate JSON data from my Mongodb database and return it to the frontend. Essentially I have nested collections like so:
Institution
|
------------> memberOrganizations
|
---------------------> associatedVIPs
Where I'm originally grabbing Institutions I can populate collections one level down using built in populate functionality.
Doing like so:
Institution.find()
.populate('memberOrganizations')
.then(function (institutions) {
console.log("All institutions, memberOrganizations populated no problem.");
return res.json(institutions);
});
The problem is coming in when I try to go populate collections inside those member organizations, and replace existing memberOrganizations data with that.
Institution.find()
.populate('memberOrganizations')
.then(function (institutions) {
var populateOrganizationOrderManagers = _.map(institutions, function (institution) {
var masterInstitution = _.cloneDeep(institution);
return new Promise(function (resolve, reject) {
var ids = _.map(institution.memberOrganizations, 'id');
Organization.find(ids).populate('associatedVIPs').then(function (orgs) {
masterInstitution.memberOrganizations = orgs;
resolve(masterInstitution);
});
});
});
return Promise.all(populateOrganizationOrderManagers)
.then(function (institutionsWithOrderManagers) {
return res.json(institutionsWithOrderManagers);
});
})
Printouts of the JSON data using console.log to print to my terminal
(Simplified all data by a bit to make it easier to make a point)
What it looks like:
[ child {
memberOrganizations:
[ { associatedVIPs:
[ { firstName: 'Gregory',
lastName: 'Parker',
email: 'info#parker2018.com',
id: '5ab94183164475010026184b' } ],
institution: '5ab940b71644750100261845',
name: 'Greg Parker',
type: 'Student',
id: '5ab941401644750100261847' },
{ associatedVIPs:
[ { firstName: 'Irma',
lastName: 'Francisco',
email: 'irmaf#houstontransporter.com',
id: '5ae348da1ef63b245a74fe2d' } ],
institution: '5ab940b71644750100261845',
name: 'Transporter Inc',
type: 'Other',
id: '5ae3488d1ef63b2c8f74fe29' } ],
name: 'Corporate',
createdAt: 2018-03-26T18:49:27.955Z,
updatedAt: 2018-07-05T15:00:02.562Z,
id: '5ab940b71644750100261845' }
What I'd like it to look like:
{ memberOrganizations:
[ {
name: 'Tau Kappa Epsilon',
type: 'Greek - Fraternity',
institution: '5a3996d47bab3401001cc1bc',
id: '5a3ae7ebdfd69201001aa54d'
associatedVIPs:
[ { firstName: 'Irma',
lastName: 'Francisco',
email: 'irmaf#houstontransporter.com',
id: '5ae348da1ef63b245a74fe2d' },
{ firstName: 'Zach',
lastName: 'Cook',
email: 'zach#google.com',
id: '5ae348da1ef63b245a74f' } ]
},
{ name: 'Farmhouse',
type: 'Greek - Fraternity',
institution: '5a3996d47bab3401001cc1bc',
id: '5a4e71e806b97a01003bd313' } ],
name: 'Troy University',
createdAt: '2017-12-19T22:46:44.229Z',
updatedAt: '2018-07-05T15:18:03.182Z',
id: '5a3996d47bab3401001cc1bc' },
{ memberOrganizations:
[ { name: 'Alpha Epsilon Pi',
type: 'Greek - Fraternity',
institution: '5a4d534606b97a01003bd2f1',
id: '5a4f95c44ec7b6010025d2fb' },
{ name: 'Alpha Delta Chi',
type: 'Greek - Sorority',
institution: '5a4d534606b97a01003bd2f1',
id: '5a74a35e1981ef01001d0633' },
{ name: 'Phi Sigma Kappa',
type: 'Greek - Fraternity',
institution: '5a4d534606b97a01003bd2f1',
id: '5a7ba61821024e0100be67b7' } ],
name: 'University of Alabama',
createdAt: '2018-01-03T22:03:50.929Z',
updatedAt: '2018-07-05T15:18:03.182Z',
id: '5a4d534606b97a01003bd2f1' }

Proper way of updating js-data relation objects

I have a linked list of objects of the same type:
GET /cards.json
[{
"id": 1,
"lesserCardId": null,
"greaterCardId": 2,
}, {
"id": 2,
"lesserCardId": 1,
"greaterCardId": 3
}, {
"id": 3,
"lesserCardId": 2,
"greaterCardId": null
}]
Resource definition:
DS.defineResource({
name: 'card',
relations: {
belongsTo: {
card: [{
localField: 'lesserCard',
localKey: 'lesserCardId'
}, {
localField: 'greaterCard',
localKey: 'greaterCardId'
}]
}
}
});
js-data correctly reads json and creates object hierarchy. What I want next is to automatically update linked card properties like this:
var card1 = DS.get('card', 1);
var card4 = DS.inject('card', {'id': 4});
card1.greaterCard = card4;
// corresponding liked object properties should be updated automatically
expect(card4.lesserCard).toBe(card1);
expect(card2.lesserCard).toBeUndefined();
I have achieved this without js-data making custom setter like this:
Object.defineProperty(Card.prototype, 'greaterCard', {
set: function (card) {
// custom logic for updating linked list structure
if (card === this.$greaterCard) {
return;
}
this.$greaterCard.lesserCard = this.$lesserCard;
this.$greaterCard = card;
if (card) {
card.lesserCard = this;
}
// updating depending properties
this.$updateCardLevel();
this.$updateCardLevelMax();
},
get: function () {
return this.$greaterCard;
}
});
But js-data introduces it's own property descriptors for relation objects. So this approach cannot be applied. I haven't found a way to hook into js-data relation property setters. I could make a separate service with method like cardService.setGreaterCard(card, greaterCard); which would update list structure, but this wouldn't be so convenient. Is there better way for updating linked objects on property change?
js-data version: 2.9.0
In JSData 2.x you would do this:
var Card = DS.defineResource({
name: 'card',
relations: {
belongsTo: {
card: [
{
localField: 'lesserCard',
localKey: 'lesserCardId',
link: false
},
{
localField: 'greaterCard',
localKey: 'greaterCardId',
link: false
}
]
}
}
});
Object.defineProperties(Card[Card.class].prototype, {
lesserCard: {
set: function (lesserCard) {
this.lesserCardId = lesserCard.id;
lesserCard.greaterCardId = this.id;
},
get: function () {
return Card.get(this.lesserCardId);
}
},
greaterCard: {
set: function (greaterCard) {
this.greaterCardId = greaterCard.id;
greaterCard.lesserCardId = this.id;
},
get: function () {
return Card.get(this.greaterCardId);
}
}
});
In JSData 3.x you would just do this:
store.defineMapper('card', {
relations: {
belongsTo: {
card: [
{
localField: 'lesserCard',
foreignKey: 'lesserCardId',
set: function (Relation, card, lesserCard, originalSet) {
lesserCard.greaterCardId = card.id;
originalSet(lesserCard);
}
},
{
localField: 'greaterCard',
foreignKey: 'greaterCardId',
set: function (Relation, card, greaterCard, originalSet) {
greaterCard.lesserCardId = card.id;
originalSet(lesserCard);
}
}
]
}
}
});

Angularjs array of nested objects from array

I have an array of position and nested user objects like so:
[
position: {
title: Developer,
user: { name: Albert }
},
position: {
title: CEO,
user: { name: Smith }
}
]
How do I get an array of [user, user] with Angularjs?
Assuming this is pseudo-code (as it's missing a few { and } and you'd need variables called Developer, Albert, CEO & Smith - I've fixed these in the working example) you can use Array.map:
var arr = [{
Position0: {
title: Developer,
user: { name: Albert }
},
{
Position1 : {
title: CEO,
user: { name: Smith }
}
}];
var result = arr.map(function(val, idx) {
return val["Position" + idx].user.name;
});
Working Example
I just tried this code, and works ...
var positions, users;
users = [];
positions = [
{
title: 'Developer',
user: { name: 'Albert' }
},
{
title: 'CEO',
user: { name: 'Smith' }
}
];
angular.forEach(positions, function(position) {
users.push(position.user);
});
console.log(users);
Firstly this thing does not need angularjs.
The way you can do that is using for each loop:
var users = [];
var positions = [{
Position0: {
title: 'Developer',
user: { name: 'Albert' }
},
Position1 : {
title: 'CEO',
user: { name: 'Smith' }
}
}]
for(var i =0; i< positions.length; i++){
for(var j in positions[i]){ //used to loop on object properties
if(positions[i].hasOwnProperty(j)){ //checking if the property is not inherited
if(positions[i][j].user){ //checking if the property exist, then only will push it to array, so that array doesnot have undefined values
users.push(positions[i][j].user);
}
}
}
}
users array will have the users.
Use angular.forEach():
var arr1=[]
var arr=[
position: {
title: Developer,
user: { name: Albert }
},
position: {
title: CEO,
user: { name: Smith }
}
];
angular.forEach(arr,function(value,key){
arr1[key]=value.position.user;
});
console.log(arr1);

Sails.js: Bootstrap encountered an error

I have the following code in my /config/bootstrap.js that inserts some dummy data for development.
/* global User */
/* global Category */
var insertDummyUsers = function() {
sails.log.info('Inserting dummy users');
var users = [
{ email: 'test#test.com' },
{ email: 'test1#testdomain.gr' },
{ email: 'test2#cnn.com'}
];
return User.create(users);
};
var insertDummyCategories = function() {
sails.log.info('Inserting dummy categories');
var categories = [
{ name: 'Furniture' },
{ name: 'Lighting' },
{ name: 'Computers' },
{ name: 'Networking' },
{ name: 'Telecommunications' },
{ name: 'TV & Audio' }
];
return Category.create(categories);
};
module.exports.bootstrap = function(cb) {
User.count().then(function(err,count){
if (count > 0) {
cb();
} else {
// Insert some dummy users
insertDummyUsers()
.then(insertDummyCategories)
.then(cb);
}
});
};
When I lift the app I am getting:
info: Inserting dummy users
info: Inserting dummy categories
error: Bootstrap encountered an error: see(below)
error: [ { name: 'Networking, id: 4, createdAt: ..., updatedAt: ... }]
[... so on]
However I can see that the data is being persisted in the database but the app is not getting lifted.
What's going on here? It really gives no clue.
EDIT
migrate: is set to drop
The Category model is defined as follows:
module.exports = {
attributes: {
name: {
type: 'string'
},
/* Associations */
subcategories: {
collection: 'Subcategory',
via: 'parentCategory'
}
}
};
I find this really bizarre, when I edit your create function like below. It works even when the callback function is empty.
I'll have to look a bit more, but this could be a bug that needs to be reported.
return Category.create(categories, function(err, returnModel) {
sails.log.debug('This should work!!! -- Error : ' + err + 'model : ' +
returnModel); });

Access data from an array with jquery

Im trying to loop through an array only i cant seem to extract the data from my array...
http://jsfiddle.net/338Ud/
var listTicker = function (options) {
var defaults = {
list: [],
startIndex: 0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function (index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function () {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
var textlist = new Array({
id: 0,
name: 'Antonia Lallement',
title: '\u003cp\u003e\u003cspan\u003eConsultant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started as a resourcer at company three months ago so I\u0026rsquo;m a new team member. Sin...',
image: 'antonia.jpg'
}, {
id: 1,
name: 'Camilla Gobel',
title: '\u003cp\u003e\u003cspan\u003eBusiness Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI joined company in 2011. As a multilingual Consultant, my initial focus was the provisi...',
image: 'camilla.jpg'
}, {
id: 2,
name: 'Mark Dorey',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Process, Subsea, Project, Safety)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eWhen I joined company I started as a resourcing specialist and worked across Search and ...',
image: 'mark.jpg'
}, {
id: 3,
name: 'Sadia Butt',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Mechanical, Piping, Structural)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI couldn\u0026rsquo;t have asked for a better company to work for! After working as a resourc...',
image: 'sadia.jpg'
}, {
id: 4,
name: 'Samantha Linnert',
title: '\u003cp\u003e\u003cspan\u003ePayroll Assistant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI began at company as an operations assistant learning to spec CVs and post jobs. Shortl...',
image: 'samantha.jpg'
}, {
id: 5,
name: 'Simon Cottenham',
title: '\u003cp\u003e\u003cspan\u003eConsultant, Middle East\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI have been with company for exactly one year now, I never would have believed that I wo...',
image: 'simon.jpg'
}, {
id: 6,
name: 'Vicky Spencer',
title: '\u003cp\u003e\u003cspan\u003ePayroll Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started my career at company in July 2012 initially covering maternity leave, managing...',
image: 'vicky.jpg'
});
$(function () {
listTicker({
list: textlist,
startIndex: 0,
trickerPanel: $('.textbox'),
interval: 3 * 1000,
});
});
you are adding object to a html .... use . operator to get the actual values
....
options.trickerPanel.fadeOut(function () {
$(this).html(value.id).fadeIn();
//--------^^^----here
}
i am taking id from the object and showing it in the div.. you can add whatever you need there..
$(this).html(value.title).fadeIn(); //to get title
fiddle here
$.each(textlist, function(index, value){
//do stuff with your array
});
Pasting just the diff, i tried to get the data here below.
From the code above.
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
The diff,
options.trickerPanel.fadeOut(function () {
$(this).html(value.bio).fadeIn();
});
The difference, is value is the entire array object being passed to the fadeOut function, accessing each elements in the array gives the result.

Categories

Resources