Last active
March 6, 2019 23:40
-
-
Save lukejoliat/7f5c61e4a2aa4132e471799cd37cf012 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import template from './recipe.html' | |
import DATA_SERVICE from '../../utils/data' | |
export default class Recipe extends HTMLElement { | |
constructor () { | |
// attach shadow DOM, initialize private recipe property, and initialize data service | |
super() | |
this._shadowRoot = this.attachShadow({ mode: 'open' }) | |
this._recipe = null | |
this.ds = new DATA_SERVICE() | |
} | |
connectedCallback () { | |
// set html content to imported template | |
this._shadowRoot.innerHTML = template | |
// attach delete method to delete button | |
this._shadowRoot | |
.querySelector('.delete') | |
.addEventListener('click', () => this._delete()) | |
} | |
_render (title) { | |
// set recipe title and text of favorite button | |
this._shadowRoot.querySelector('.recipe-title').innerHTML = title | |
this._shadowRoot.querySelector('.favorite').innerHTML = this._recipe | |
.favorite | |
? 'Unfavorite' | |
: 'Favorite' | |
} | |
_delete () { | |
// delete recipe or display error | |
try { | |
await this.ds.deleteRecipe(this._recipe.id) | |
} catch (e) { | |
console.error(e) | |
alert( | |
'Sorry, there was a problem deleting the recipe. Please, try again.' | |
) | |
} | |
} | |
get recipe () { | |
// getter for recipe | |
return this._recipe | |
} | |
set recipe (recipe = {}) { | |
// setter for recipe which triggers render method | |
this._recipe = recipe | |
this._render(this._recipe.title) | |
} | |
} | |
window.customElements.define('recipe-item', Recipe) |
- For unknown reason
_render
acceptsthis._recipe.title
as an argument, but accessesthis._recipe.favorite
inside. Broken levels of abstraction: should either take wholerecipe
data object or both primitive values as arguments, or take all values fromthis._recipe
inside.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
_delete
).async
to make it compile, the click event handler would unexpectedly return a promise to the browser that calls it.