Skip to content

Instantly share code, notes, and snippets.

@luc4leone
Created August 26, 2015 07:07
Show Gist options
  • Save luc4leone/5480f7416320e2a1b996 to your computer and use it in GitHub Desktop.
Save luc4leone/5480f7416320e2a1b996 to your computer and use it in GitHub Desktop.
var model = {
currentCat: null,
cats: [
{
catName: "joe",
catCount: 0,
imgSource: "img/cat0.jpg"
},
{
catName: "pin",
catCount: 0,
imgSource: "img/cat1.jpg"
},
{
catName: "jen",
catCount: 0,
imgSource: "img/cat2.jpg"
},
{
catName: "tom",
catCount: 0,
imgSource: "img/cat3.jpg"
},
{
catName: "osvald",
catCount: 0,
imgSource: "img/cat4.jpg"
}
]
};
var octopus = {
init: function(){
catNavView.init();
model.currentCat = model.cats[0];
catPreView.init();
},
getCats: function(){
return model.cats;
},
getCurrentCat: function(){
return model.currentCat;
},
incrementCount: function(){
model.currentCat.catCount++;
catPreView.render();
}
}
var catNavView = {
init: function(){
this.catNavEl = document.getElementById("cat-nav"); //dichiaro la pro-
//prietà e siccome è dentro a una function def metto davanti this
//perchè non var?
this.render(); //se non ci fosse questo statement octopus.init non basterebbe
},
render: function(){
/* devo scrivere l'html dei bottoni della nav. a ciascuno di essi
devo attaccare il listener
*/
// pulisco ul
this.catNavEl.innerHTML = "";
var cats = octopus.getCats();
for (var i = 0; i < cats.length; i++) {
var cat = cats[i]; //rende concreto l'elemento su cui sto lavorando
//durante il loop
var liEl = document.createElement("li");
liEl.textContent = cat.catName; //avevo messo
//liEl.textContent(cat.name);
this.catNavEl.appendChild(liEl);
/*
ho provato a usare this.liEl nelle ultime righe (3 posti)
al posto di var e poi liEl da solo e il codice funziona.
la mia ipotesi è che this.liEl definisce una proprità
dell'oggetto che poi posso usare fuori dalla funzione.
invece var liEl definisce una variabile locale.
*/
}
}
};
var catPreView = {
init: function(){
this.catPreviewEl = document.getElementById("cat-preview");
this.catNameEl = document.getElementById("cat-name");
this.catCountEl = document.getElementById("cat-count");
this.catImgEl = document.getElementById("cat-img");
this.render();
},
render: function(){
var currentCat = octopus.getCurrentCat();
this.catNameEl.textContent = currentCat.catName;
this.catCountEl.textContent = currentCat.catCount;
this.catImgEl.src = currentCat.imgSource;
this.catImgEl.addEventListener("click", function(){
octopus.incrementCount();
})
}
}
octopus.init(); //me l'ero dimenticato
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment