Skip to content

Commit

Permalink
react hooks in omi
Browse files Browse the repository at this point in the history
  • Loading branch information
张磊 committed Oct 31, 2018
1 parent 360aaaf commit 0eaba2d
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 56 deletions.
112 changes: 68 additions & 44 deletions packages/omi/examples/use/b.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/omi/examples/use/b.js.map

Large diffs are not rendered by default.

24 changes: 21 additions & 3 deletions packages/omi/examples/use/main.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,35 @@
import { define, render } from '../../src/omi'

define('my-counter', function() {
const [count, setCount] = this.useData(0)
const [count, setCount] = this.use({
data: 0,
effect: function() {
document.title = `The num is ${this.data}.`
}
})

this.useEffect(() => {
document.title = `The num is ${count}.`
const [items, setItems] = this.use({
data: [{ text: 'Omi' }],
effect: function() {
console.log(`The items count is ${this.data.length}.`)
}
})

return (
<div>
<button onClick={() => setCount(count - 1)}>-</button>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>+</button>

<ul>
{items.map(item => {
return <li>{item.text}</li>
})}
</ul>
<button onClick={() => setItems([...items, { text: 'new item' }])}>
add
</button>
<button onClick={() => setItems([])}>empty</button>
</div>
)
})
Expand Down
24 changes: 16 additions & 8 deletions packages/omi/src/define.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,33 @@ export function define(name, ctor) {
return ctor.call(this)
}

useData(value) {
beforeRender() {
this._useId = 0
}

use(option) {
this._useId++
const updater = newValue => {
this._useMap[this._useId] = newValue
const item = this._useMap[updater.id]

item.data = newValue

this.update()
this._effectFn()
item.effect && item.effect()
}

updater.id = this._useId
if (!this._isInstalled) {
return [value, updater]
this._useMap[this._useId] = option
return [option.data, updater]
}
return [this._useMap[this._useId++], updater]

return [this._useMap[this._useId].data, updater]
}

installed() {
this._isInstalled = true
}
useEffect(fn) {
this._effectFn = fn
}
}
customElements.define(name, Element)
}
Expand Down

0 comments on commit 0eaba2d

Please sign in to comment.