Published
Edited
Aug 5, 2019
Insert cell
Insert cell
Insert cell
{
const handler = {
set (target, prop, value) {
if (value < 10) {
console.log(`現在${value}kgです。`)
target[prop] = value
return true
}
throw new Error(`食事内容を変更してください。`)
}
}
const cat = new Proxy({ weight: 2 }, handler)
cat.weight += 1 // 現在3kgです。
cat.weight += 2 // 現在5kgです。
cat.weight += 10 // Error: 食事内容を変更してください。
}
Insert cell
Insert cell

{
const { observable, observe, Action } = dob
const dog = observable({
name: 'ポチ',
gender: 'male',
age: 2,
condition: {
happy: true,
hungry: false
}
})
// observe定義時に、渡した関数が即時実行されます。
observe(() => {
console.log(dog.name, dog.gender)
if (dog.condition.hungry) {
console.log('ご飯を食べさせましょう。')
}
})
// ポチ male
// observe内でアクセスされたpropertyを変更すると検知対象となります。
dog.name = 'ポチ太郎'
// ポチ太郎 male
// observe内で参照されていないpropertyを変更しても何も起きません。
dog.age += 1
// Actionを使うことで、値を複数回変更しても、コールバックが一度のみ実行されるようになります。
Action(() => {
dog.name = 'ポチ美'
dog.gender = 'female'
})
// ポチ美 female
// object を持つ property についても同様に扱えます。
dog.condition.hungry = true
// ポチ美 female
// ご飯を食べさせましょう。
}
Insert cell
Insert cell
Insert cell
{
const { observable, observe, Action } = dob
const shop = observable({
fruits: ['🍎', '🍊', '🍌']
})
observe(() => {
console.log(shop.fruits, 'フルーツが変更されました')
})
// Proxy {}, フルーツが変更されました。
// 以下を実行しても、配列自体は同じものと見なされるため、コールバックが実行されない。
shop.fruits.push('🍓')
}
Insert cell
Insert cell
{
const { observable, observe, Action } = dob
const tree = observable({
root: 1,
leaf: 100
})
function treeNode () {
return tree.root + tree.leaf
}
observe(() => {
console.log(tree.root, treeNode())
})
// 1 101
// treeNodeで参照しているため、以下の処理は検知対象となる。
++tree.leaf
// 1 102
}
Insert cell
Insert cell
{
const { observable, observe, Action } = dob
const game = observable({
count: 1
})
observe(() => {
++game.count // InternalError: too much recursion
})
}
Insert cell
{
const { observable, observe, Action } = dob
const game = observable({
count: 1
})
observe(() => {
Action(() => {
++game.count // no loop
})
})
}
Insert cell
Insert cell
{
const { observable, observe, Action } = dob
const game = observable({
isPlay: false,
title: '🦍ワールド'
})
observe(() => {
console.log(game.isPlay ? 'ゲームプレイ中' : 'ゲームしてません')
if (game.isPlay) {
console.log(`「${game.title}」をプレイしています。`)
}
})
// ゲームしてません
// 以下のproperty変更は、最後に呼び出されたコールバックで読み取られていないため、呼び出されません。
game.title = '🐈の大冒険'
game.isPlay = true
// ゲームプレイ中
// 「🐈の大冒険」をプレイしています。
// 以下のproperty変更は、最後に呼び出されたコールバックで読み取られたため、呼び出されます。
game.title = '🐶クエスト'
// ゲームプレイ中
// 「🐶クエスト」をプレイしています。
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more