Skip to content

Instantly share code, notes, and snippets.

@lukejoliat
Last active March 6, 2019 23:40
Show Gist options
  • Save lukejoliat/7f5c61e4a2aa4132e471799cd37cf012 to your computer and use it in GitHub Desktop.
Save lukejoliat/7f5c61e4a2aa4132e471799cd37cf012 to your computer and use it in GitHub Desktop.
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)
@sompylasar
Copy link

  1. Unexpected await in a non-async function (method _delete).
  2. If it were async to make it compile, the click event handler would unexpectedly return a promise to the browser that calls it.

@sompylasar
Copy link

  1. For unknown reason _render accepts this._recipe.title as an argument, but accesses this._recipe.favorite inside. Broken levels of abstraction: should either take whole recipe data object or both primitive values as arguments, or take all values from this._recipe inside.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment