Skip to content

Instantly share code, notes, and snippets.

@brnrdog
Last active August 12, 2016 14:59
Show Gist options
  • Save brnrdog/0562f370bb42c176adeb3a489b78108f to your computer and use it in GitHub Desktop.
Save brnrdog/0562f370bb42c176adeb3a489b78108f to your computer and use it in GitHub Desktop.
things-fetcher.js
import $ from 'jquery'
const ENDPOINT = 'api/v1/some-endpoint'
const DEFAULTS = {
loadingMsg: 'Loading. Please wait...',
successMsg: 'Things fetched with success.',
errorMsg: 'Sorry. Try again later.'
}
class BaseComponent {
constructor (el) {
this.$el = el
this.register()
}
register () {
this.$element.data(this._parseName(), this)
}
_parseName () {
return this.constructor.name
.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-')
.toLowerCase()
}
}
class ThingsFetcher extends BaseComponent {
constructor (el, options) {
super(el)
this.options = Object.assign({}, DEFAULTS, options)
}
init () {
this._fetch = this._fetch.bind(this)
this._onSuccess = this._onSuccess.bind(this)
this._onError = this._onError.bind(this)
this._onLoading = this._onLoading.bind(this)
this.bindListeners()
}
bindListeners () {
this.$el.on('click', this._fetch)
}
_fetch () {
this.$el.removeClass('success failure')
$.get(ENDPOINT).then(this._onSuccess, this._onError, this._onLoading)
}
_onSuccess () {
this._updateUI({
disabled: false,
className: 'success',
text: this.$el.text
})
window.alert(this.options.successMsg)
}
_onError () {
this._updateUI({
disabled: false,
className: 'failure',
text: this.$el.text
})
window.alert(this.options.errorMsg)
}
_onLoading () {
this._updateUI({
disabled: true,
className: '',
text: this.options.loadingMsg
})
}
_updateUI ({ disabled, className, text }) {
this.$el.prop('disabled', disabled)
this.$el.addClass(className)
this.$el.text(text)
}
}
export default ($el) => new ThingsFetcher($el).init()
export { ThingsFetcher as Component }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment