update example

pull/1/head
yann300 7 years ago
parent bd52d80022
commit 7be2e0bfda
  1. 46
      best-practices.md

@ -52,21 +52,14 @@ var css = csjs`
`
class UserCard {
constructor (opts = {}) {
constructor (api, events, opts = {}) {
var self = this
self.event = new EventManager()
self._api = opts.api
self.opts = opts
self._api = api
self._consumedEvents = events
self._view = undefined
self.state = {
title: opts.title,
name: opts.name,
surname: opts.surname,
totalSpend: 0,
_nickname: opts.nickname,
_funds: self._api.getUserFunds()
}
var events = opts.events
events.funds.register('fundsChanged', function (amount) {
if (amount < self.state._funds) self.state.totalSpend += self.state._funds - amount
@ -77,7 +70,7 @@ class UserCard {
}
render () {
var self = this
var el = yo`
var view = yo`
<div class=${css.userCard}>
<h1> @${self.state._nickname} </h1>
<h2> Welcome, ${self.state.title || ''} ${self.state.name || 'anonymous'} ${self.state.surname} </h2>
@ -86,17 +79,16 @@ class UserCard {
<button class=${css.clearFunds} onclick=${e=>self._spendAll.call(self, e)}> spend all funds </button>
</div>
`
if (self._view) yo.update(self._view, el)
else self._view = el
if (!self._view) {
self._view = view
}
return self._view
}
update (state = {}) {
var self = this
if (!self._view) self._constraint('first initialize view by calling `.render()`')
if (state.hasOwnProperty('title')) self.state.title = state.title
if (state.hasOwnProperty('name')) self.state.name = state.name
if (state.hasOwnProperty('surname')) self.state.surname = state.surname
self.render()
update () {
yo.update(this._view, this.render())
}
setNickname (name) {
this._nickname = name
}
getNickname () {
var self = this
@ -139,9 +131,10 @@ setInterval(function () {
// 2. EXAMPLE USAGE
var UserCard = require('./user-card')
var usercard = new UserCard({
api: { getUserFunds, clearUserFunds },
events: { funds: funds.event },
var usercard = new UserCard(
{ getUserFunds, clearUserFunds },
{ funds: funds.event },
{
title: 'Dr.',
name: 'John',
surname: 'Doe',
@ -150,5 +143,8 @@ var usercard = new UserCard({
var el = usercard.render()
document.body.appendChild(el)
setTimeout(function () { usercard.update({ title: 'Prof.' }) }, 5000)
setTimeout(function () {
userCard.setNickname('new name')
usercard.update()
}, 5000)
```

Loading…
Cancel
Save