jQuery, on hover show text snippet in another div - javascript

I'm trying to build an interactive banner that when you hover over the banner, you can hover over each image and see a snippet of text.
Im trying to make this snippet of text appear in my div titled 'textbox' only im struggling to make it change when the mouse leaves each image (you will have to see my fiddle for an example)
Let each image load BEFORE hovering over the html blue box...
http://jsfiddle.net/uEDBA/3/
jQuery
$(document).ready(function () {
$(function () {
var people = [{
id: 1,
name: 'Adam',
bio: 'This is Adam\'s Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'justin.jpg'
}, {
id: 2,
name: 'Brian',
bio: 'This is Brian\' Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'chris.jpg'
}, {
id: 3,
name: 'Charlie',
bio: 'This is Charlie\'s Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'sam.jpg'
},
];
w = 750;
h = 450;
var counter = 0;
(function nextFade() {
counter++;
var data = people[Math.floor(Math.random() * people.length)];
var figure = $('<figure style="float:left; width:150px; height:150px; background:red;" />');
var information = '<img src="http://www.placekitten.com/150/150" /><figcaption><h6>Meet ' + data.name + '</h6><p>' + data.bio + '</p>Read about ' + data.name + '. </figcaption>';
figure.html(information).appendTo('.interactive-banner-faces').hide().fadeIn(100, function () {
if (counter < 15) {
nextFade();
} else {
$('.interactive-banner-faces').children(':nth-child(12n+1), :nth-child(12n+2), :nth-child(12n+3)').addClass('rightTxt');
// On mouseover, fadeout the text overlay so we can play with the banner
$('.interactive-banner').on('mouseenter', function () {
$('.textbox').html(data.bio).fadeIn();
$('.overlay').stop().animate({
'top': '-450px'
}, 200, 'easeInCirc');
}).on('mouseleave', function () {
$('.textbox').html('').fadeOut();
$('.overlay').stop().animate({
'top': '0'
}, 600, 'easeOutCirc');
});
};
});
})();
});
});

Related

Create nested list items with given depths in JavaScript

I'm trying to make nested list items with the data below:
It creates the right indentation when depths are sorted with -1 +1 but I can't make the perfect indentation. Any help will be appreciated.
const data = [
{depth: 1, title: "Some Title Goes Here - First Title", url: "#some-title-goes-here-first-title-prs7ztig15"},
{depth: 2, title: "Yuck Almost Got it!", url: "#yuck-almost-got-it-qlx0i4727h"},
{depth: 1, title: "Whoops! Something went Wrong", url: "#whoops-something-went-wrong-qoflcur4iw"},
{depth: 1, title: "Don't Worry We Get You Covered", url: "#dont-worry-we-get-you-covered-ug4kxqz4kp"},
{depth: 3, title: "I Hate Writing Titles", url: "#i-hate-writing-titles-jrlw78vulm"},
{depth: 4, title: "Gonna Start to Lorem", url: "#gonna-start-to-lorem-whzh8e3qus"},
{depth: 2, title: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam, voluptate!", url: "#lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit-quisquam-voluptate-agxlhkvs8c"},
{depth: 1, title: "Consectetur adipisicing elit. Quo, corporis!", url: "#consectetur-adipisicing-elit-quo-corporis-4xurvdulcn"},
{depth: 1, title: "Dolor sit amet, consectetur adipisicing elit. Fugiat, quae?", url: "#dolor-sit-amet-consectetur-adipisicing-elit-fugiat-quae-txu46oaitk"},
{depth: 2, title: "Adipisicing elit. Dolor, rem.", url: "#adipisicing-elit-dolor-rem-x6coih7o36"},
{depth: 3, title: "Elit. Consequuntur, cum.", url: "#elit-consequuntur-cum-zqyhfglbd4"},
{depth: 4, title: "Ipsum dolor sit amet.", url: "#ipsum-dolor-sit-amet-sz09eh07ma"},
{depth: 2, title: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo, corporis!", url: "#lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit-quo-corporis-18g13jn4j5"}]
function getTOCOutput(data) {
if (data.length < 1) return '';
let tocOutput = "<ul>";
let currentDepth = data[0].depth;
let c = data.length;
for (let i = 0; i < c; i++) {
let itemDepth = data[i].depth;
if (currentDepth === itemDepth) {
tocOutput += '<li>' + data[i].title + '';
} else if (currentDepth < itemDepth) {
tocOutput += '<ul><li>' + data[i].title + '';
} else {
tocOutput += '</li>' + '</ul>'.repeat(currentDepth - itemDepth) + '<li>' + data[i].title + '</li>';
}
currentDepth = data[i].depth;
}
tocOutput += "</ul>";
return tocOutput;
}
document.body.innerHTML += getTOCOutput(data);
You can use two while loops inside the for loop in order to account for the depth changes. They repeat until the current depth is right:
function getTOCOutput(data) {
let currentDepth = 0;
let tocOutput = "";
for (let {depth, title, url} of data) {
while (depth > currentDepth) {
tocOutput += "<ul>";
currentDepth++;
}
while (depth < currentDepth) {
tocOutput += "</ul>";
currentDepth--;
}
tocOutput += '<li>' + title + '';
}
return tocOutput;
}
let data = [{depth: 1, title: "Some Title Goes Here - First Title", url: "#some-title-goes-here-first-title-prs7ztig15"},{depth: 2, title: "Yuck Almost Got it!", url: "#yuck-almost-got-it-qlx0i4727h"},{depth: 1, title: "Whoops! Something went Wrong", url: "#whoops-something-went-wrong-qoflcur4iw"},{depth: 1, title: "Don't Worry We Get You Covered", url: "#dont-worry-we-get-you-covered-ug4kxqz4kp"},{depth: 3, title: "I Hate Writing Titles", url: "#i-hate-writing-titles-jrlw78vulm"},{depth: 4, title: "Gonna Start to Lorem", url: "#gonna-start-to-lorem-whzh8e3qus"},{depth: 2, title: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam, voluptate!", url: "#lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit-quisquam-voluptate-agxlhkvs8c"},{depth: 1, title: "Consectetur adipisicing elit. Quo, corporis!", url: "#consectetur-adipisicing-elit-quo-corporis-4xurvdulcn"},{depth: 1, title: "Dolor sit amet, consectetur adipisicing elit. Fugiat, quae?", url: "#dolor-sit-amet-consectetur-adipisicing-elit-fugiat-quae-txu46oaitk"},{depth: 2, title: "Adipisicing elit. Dolor, rem.", url: "#adipisicing-elit-dolor-rem-x6coih7o36"},{depth: 3, title: "Elit. Consequuntur, cum.", url: "#elit-consequuntur-cum-zqyhfglbd4"},{depth: 4, title: "Ipsum dolor sit amet.", url: "#ipsum-dolor-sit-amet-sz09eh07ma"},{depth: 2, title: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo, corporis!", url: "#lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit-quo-corporis-18g13jn4j5"},];
document.body.insertAdjacentHTML("beforeend", getTOCOutput(data));

Unable to view inline images in the body of a markdown file in GatsbyJS

I am trying to display images from a Markdown file especially from the body of the markdown file but unable to see them.
I am using the recommended plugin configuration by the official GatsbyJS documentation for embedding images in Markdown files. However, I am unable to achieve the same. I can view the images from the frontmatter using GraphQL queries but unable to view the body inline images in the markdown file.
const guid = process.env.NETLIFY_GOOGLE_ANALYTICS_ID;
module.exports = {
siteMetadata: {
title: 'Apple Software',
description: 'my theme',
contact: {
phone: '+91 999999999',
email: 'info#abcxyz.com',
},
menuLinks: [
{
name: 'Services',
link: '/services',
},
{
name: 'Team',
link: '/team',
},
{
name: 'Testimonials',
link: '/testimonials',
},
{
name: 'Blog',
link: '/blog',
},
{
name: 'Contact',
link: '/contact',
},
{
name: 'Work',
link: '/work',
},
{
name: 'Courses',
link: '/carousel',
},
{
name: 'Careers',
link: '/careers',
},
],
},
plugins: [
'gatsby-plugin-sass',
'gatsby-transformer-json',
'gatsby-transformer-remark',
'gatsby-plugin-react-helmet',
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/pages`,
name: 'pages',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/data`,
name: 'data',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/images`,
name: 'images',
},
},
{
resolve: 'gatsby-plugin-google-analytics',
options: {
trackingId: guid ? guid : 'UA-XXX-1',
// Puts tracking script in the head instead of the body
head: false,
},
},
`gatsby-plugin-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 590,
},
},
],
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
gatsbyRemarkPlugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 1200,
},
},
],
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/pages`,
},
},
],
};
and here is the markdown file
---
path: '/services/accounting'
title: 'Accounting'
date: 2018-11-18T12:33:46+10:00
image: 'services/default.png'
---
Lorem markdownum aequalis strigis. _Saetigeri iubeas_, vultu huic alvum nondum
de obside ut laniavit arbor palmis, cum quin. Rupes vetat videndo, armigerae
crimen habet Priamum nec.
## Ne verba patulosque numen vix libet
![Default Image](./default.png)
Agitabitur signa lympha; non lacunae, mox cum tumulis quoque triste dictis.
Ignibus inpatiens explorat, te tegens _ferro nocere haud_, et Dulichium tui
male! Quo sed [fuit flexit et](#vexant-achivi) hic die solido, gloria?
1. Cum det dixit Parcarum qui spemque est
2. Exit ex huic
3. Quod consiste agitataque claustraque vicina videt lacertis
4. Loquor videt
5. Ardua non igne caelesti coniugis cognovi diversorum
6. Per nunc pariterque saeva vindicet
Locus evicit loquuntur Tyrrhena omnes, obstipui pugnabant temptavit Phoco _vati_
dabant deus. Memorata haberet sepulcrales gentisque dum sic, in flumina templa!
Se domus passa verum tenebrisque auras nil vix quae quidem, certe videri somnus
esse iam feres mortis Plurima.
## Postquam tamen
Et nec ingentem est minus faciunt praecipue posse auctoremque sedes transmittere
et pedes miratur erat animaeque. Tellus admonuit humanam funes, sagittis et
licet! Inserui quamvis Clymeni.
- Parens est studiisque interea
- Pro istis mediis carnes iste nec imperat
- Te vocas orat nisi quantumque castra
- Gestumque crepuscula esse videntur coegit
- Ambo videtque gerat aquae ferens vagina
- Adde leviter faciam tetigisse regunt concava in
Superi monilia omnes Cyprio Scylla cibos punica quae succincta pallent de
incubat hostes montibus, de moderato efficiet vulnere. Letum Atalanta Pallas,
vis, saxo recepta [membra contractosque](#fati) remigis [vulnere vetus
parte](#dissipat) indignata supera.
The image in the frontmatter (Header) is working fine. But the same image (default.png) is not showing up from the body of this markdown file.

How can I get the same object in the visitor area as I get in the admin area without the user $uid

Currently on a blog website like I got a problem I didn't expect when I start building it...
I build it like this:
• A admin area where you have to login where you can write/delete articles.
• A public area where you don't need to login where you can see the articles write in the admin area.
My database is build like below as you can see every user got a $uid. So because of how it's build my service look like this:
{
"articles" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORxrYnctixsx5sQ5DM" : {
"author" : "Zinedine Zidane",
"categories" : [ "Football", "Tennis" ],
"content" : "<p>Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.</p>",
"date" : 1539158014424,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41666967_311898482736538_5532086598150712503_n.jpg?alt=media&token=6b13fe37-357e-45db-8d0e-4436e166d359",
"name" : "Thalassio otium quem et hortaretur. \t"
},
"-LORy85GKdT9U9p_Iolk" : {
"author" : "David Kidouille",
"categories" : [ "Football", "ChatMignon" ],
"content" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"date" : 1539158086263,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/36981961_1869531810009121_4498273348232413184_n.jpg?alt=media&token=47fc2e67-d198-4533-8939-abc5d3dbed51",
"name" : "Omni habere atque perpetuae sic."
},
"-LOTQNaI7ry3WRavCjNt" : {
"author" : "Sophia Green",
"categories" : [ "Espresso", "Title" ],
"content" : "<p>Harum trium sententiarum nulli prorsus assentior. Nec enim illa prima vera est, ut, quem ad modum in se quisque sit, sic in amicum sit animatus. Quam multa enim, quae nostra causa numquam faceremus, facimus causa amicorum! precari ab indigno, supplicare, tum acerbius in aliquem invehi insectarique vehementius, quae in nostris rebus non satis honeste, in amicorum fiunt honestissime; multaeque res sunt in quibus de suis commodis viri boni multa detrahunt detrahique patiuntur, ut iis amici potius quam ipsi fruantur.</p><p>Ibi victu recreati et quiete, postquam abierat timor, vicos opulentos adorti equestrium adventu cohortium, quae casu propinquabant, nec resistere planitie porrecta conati digressi sunt retroque concedentes omne iuventutis robur relictum in sedibus acciverunt.</p><p>Non ergo erunt homines deliciis diffluentes audiendi, si quando de amicitia, quam nec usu nec ratione habent cognitam, disputabunt. Nam quis est, pro deorum fidem atque hominum! qui velit, ut neque diligat quemquam nec ipse ab ullo diligatur, circumfluere omnibus copiis atque in omnium rerum abundantia vivere? Haec enim est tyrannorum vita nimirum, in qua nulla fides, nulla caritas, nulla stabilis benevolentiae potest esse fiducia, omnia semper suspecta atque sollicita, nullus locus amicitiae.</p>",
"date" : 1539182528987,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/37112713_499156913858390_6321776699583234048_n.jpg?alt=media&token=dea02d84-dcc8-427e-92d1-92529499e052",
"name" : "Plerisque honoribus inventu in verae descendant quas in graves enim"
}
}
},
"contact" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"adress" : "Bla Bla Bla",
"email" : "michel#gmail.com",
"facebook" : "www.facebook.com",
"phone" : "0606060606"
}
},
"evenements" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORx0d49L5W1OHbaPkz" : {
"content" : "<p>Eodem tempore Serenianus ex duce, cuius ignavia populatam in Phoenice Celsen ante rettulimus, pulsatae maiestatis imperii reus iure postulatus ac lege, incertum qua potuit suffragatione absolvi, aperte convictus familiarem suum cum pileo, quo caput operiebat, incantato vetitis artibus ad templum misisse fatidicum, quaeritatum expresse an ei firmum portenderetur imperium, ut cupiebat, et cunctum.</p>",
"dateEnd" : "20/08/1995",
"dateStart" : "17/08/1995",
"name" : "Stand de tir au pigeon",
"place" : "33 rue de la Liberté, Bourgoin Jallieu"
}
}
},
"medias" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORymdySlsQ82_rZ6kk" : {
"description" : "Bla Bla Bla Bla",
"titre" : "30 ans de michel",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41466540_333985383837957_6494746608337518152_n.jpg?alt=media&token=079311d7-c42e-4e21-933e-36573e88a893"
},
"-LORyzf8ft5hS_MV_B10" : {
"description" : "klsjbvsjdkbvjkshd",
"titre" : "Bla Bla bla",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41532985_724838064517122_5880047170186967403_n.jpg?alt=media&token=86632def-47b3-4b30-84c9-c9af571da17d"
}
}
},
"sports" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORzZ2xq_JszbFaFyyn" : {
"description" : "<p>Nec vox accusatoris ulla licet subditicii in his malorum quaerebatur acervis ut saltem specie tenus crimina praescriptis legum committerentur, quod aliquotiens fecere principes saevi: sed quicquid Caesaris implacabilitati sedisset, id velut fas iusque perpensum confestim urgebatur impleri.</p>",
"handisport" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/42004027_2218122771593693_1511293494740179714_n.jpg?alt=media&token=430ddee9-a818-44ac-b80c-2483be38f1c0",
"name" : "Football",
"nbrPlayer" : 10,
"partTime" : 30
}
}
}
}
My Service in the Admin Area where I can access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
import { AuthService } from './auth.service';
export interface Article {
name: string,
author: string,
categories: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles/${this.uid}`).snapshotChanges()
.pipe(map(actions =>
actions.map(a => ({ key: a.key, ...a.payload.val() }))
))
.pipe(tap(next => {
this.store.set('articles', next);
})
);
constructor(
private store: Store,
private db: AngularFireDatabase,
private authService: AuthService
) {}
get uid() {
return this.authService.user.uid;
}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
addArticle(article: Article) {
return this.db.list(`articles/${this.uid}`).push(article);
}
updateArticle(key: string, article: Article) {
return this.db.object(`articles/${this.uid}/${key}`).update(article);
}
removeArticle(key: string) {
return this.db.list(`articles/${this.uid}`).remove(key);
}
}
My Service in the Admin Area where I can't access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles`).snapshotChanges()
.pipe(map(userId =>
userId.map(a => ({ ...a.payload.val() }))
)).pipe(tap(next => {
this.store.set('articles', next);
}));
constructor(
private store: Store,
private db: AngularFireDatabase
) {}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
}
So When I call the service for get my articles in the admin area I get and in the public area I get.
I find a way to get the value but with this way I lose the key object.
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
How can I get the same object in the visitor area as I get in the admin area ?

MongoDB relations child to parent

I create an Meteor application where have two collections, ActivityCards and Users. I have a reference to the User inside my ActivityCard collections like this:
{
"_id" : "T9QwsHep3dMSRWNTK",
"cardName" : "Guntnauna",
"activitycardType" : 10,
"startDate" : "1952-08-09",
"remainingHours" : 0,
"activities" : [
{
"activityName" : "Cfuw",
"activityTotal" : "5",
"activityEmployee" : "Smamnktl",
"activityDate" : "1960-07-16"
},
...
],
"customerID" : "z9hXczmWaf7wgdAtj",
"isArchived" : 0
}
customerID contains an id to the following user collection:
{
"_id" : "9mXAZkmfpKMPvQY8Y",
"createdAt" : ISODate(),
"services" : {
"password" : {
"bcrypt" : ""
}
},
"emails" : [
{
"address" : "topony#mailinator.com",
"verified" : false
}
],
"profile" : {
"relationNumber" : "962",
"companyName" : "Snider Kinney Co",
"locationStreet" : "Ullamco eaque consequatur aspernatur consectetur eiusmod eligendi enim rerum consectetur asperiores officia eius itaque expedita dolorum",
"locationPostal" : "Sit inventore asperiores est anim commodo non fugiat consequat Voluptatem tempore sunt culpa magni",
"locationCity" : "Ipsum et fugit pariatur Nobis eveniet neque veniam perferendis eius ut quo excepteur consequatur voluptatem architecto",
"contactName" : "Julian Moran",
"contactPhone" : "+388-14-8339022",
"isArchived" : 0
},
"roles" : {
"customers" : [
"customer"
]
}
}
I am new to MongoDB and don't know if this is a properly configured relation In the documentation I mostly find relations from parent to child and not the other way around.
I am wondering what would you guys suggest for this type of relation.
How to save them, get the data from both collections, etc.
If my code can be used I would like to know how to get the relations from child to parent and display them. currently I only used the find() method from MongoDB and mapped the data into separate values.
You can have such a relation in your mongodb collection. If you are using mongoose you can define them in your schema like this:
customerId:{{ type: mongoose.Schema.ObjectId, ref: 'user' }}
and you can reach the parent from child with mongoose populate.
for more information see
https://mongoosejs.com/docs/populate.html

backbone marionette related models

I'm trying to list some posts with their related users. Each post has a title some text and a userId like this:
[{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"text": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
How can I relate my post model to the users model? It works like I tried it below but it's quick and dirty. Do I need to use backbone-relational? I just don't know if backbone-relation is an overkill for just one one-2-many relation in my application.
var fetchingPosts = BackboneApplication.request("post:entities");
var postsListLayout = new List.Layout();
$.when(fetchingPosts).done(function(posts){
$.each(posts.models, function(i, post){
var username = BackboneApplication.request("user:entity", post.get("userId"));
$.when(username).done(function(user){
post.set("name",user.get("name"));
});
});
var contactsListView = new List.Posts({
collection: posts
});
EDIT due to the question my post model looks like this:
Entities.Post = Backbone.Model.extend({
url : "url_to_rest_api",
idAttribute : 'id'
});
EDIT 2: Is this following parse function possible for the fact that I'm not able to change my rest api.
parse: function(response) {
user = BackboneApplication.request("user:entity", response.userId)
this.user = new User(user);
return response'
}
One option is to have your posts service return fully loaded "Post" models that look like:
[{
//not just an id anymore
"user": {"id":1, "username":"Fred", "email":"bob#bob.com"},
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"text": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
Then in your Post model's parse method you can do the following:
parse: function(response) {
//convert raw user json to backbone model
response.user = new User(response.user);
return response'
}
This avoids the relational dependency, but requires your rest endpoint to load user data with all post data. You could have your endpoints be specific but have your service layer be general so the concept of post and user are still loosely coupled
//pseudo
def getPost(id) {
def post = postService.getPost(id);
post.user = userService.getUser(post.userid)
render post as json
}

Categories