Initial view implementation (fix #3).

This commit is contained in:
Julien Fontanet 2015-04-13 20:23:43 +02:00
parent 653a9526f5
commit 783ab0b611
3 changed files with 120 additions and 0 deletions

View File

@ -21,6 +21,8 @@
],
"dependencies": {
"babel-runtime": "^5",
"lodash.bind": "^3.1.0",
"lodash.callback": "^3.1.1",
"lodash.foreach": "^3.0.2",
"make-error": "^1.0.0"
},

View File

@ -0,0 +1,40 @@
import Collection from './'
import View from './view'
const users = new Collection()
users.getId = (user) => user.name
const activeUsers = new View(users, 'active')
activeUsers.on('add', console.log)
activeUsers.on('update', console.log)
activeUsers.on('remove', console.log)
users.add({
name: 'bob'
})
users.add({
name: 'clara',
active: true
})
users.add({
name: 'ophelia'
})
users.add({
name: 'Steve',
active: true
})
setTimeout(function () {
console.log('-----')
users.set({
name: 'ophelia',
active: true
})
users.set({
name: 'Steve'
})
}, 10)

View File

@ -0,0 +1,78 @@
import bind from 'lodash.bind'
import createCallback from 'lodash.callback'
import forEach from 'lodash.foreach'
import Collection from './'
// ===================================================================
export default class View extends Collection {
constructor (collection, predicate, thisArg) {
super()
this._collection = collection
this._predicate = createCallback(predicate, thisArg)
// Bound versions of listeners.
this._onAdd = bind(this._onAdd, this)
this._onUpdate = bind(this._onUpdate, this)
this._onRemove = bind(this._onRemove, this)
// Register listeners.
this._collection.on('add', this._onAdd)
this._collection.on('update', this._onUpdate)
this._collection.on('remove', this._onRemove)
}
destroy () {
this._collection.removeListener('add', this._onAdd)
this._collection.removeListener('update', this._onUpdate)
this._collection.removeListener('remove', this._onRemove)
}
add () {
throw new Error('a view is read only')
}
clear () {
throw new Error('a view is read only')
}
set () {
throw new Error('a view is read only')
}
update () {
throw new Error('a view is read only')
}
_onAdd (items) {
const {_predicate: predicate} = this
forEach(items, (value, key) => {
if (predicate(value, key, this)) {
super.add(key, value)
}
})
}
_onUpdate (items) {
const {_predicate: predicate} = this
forEach(items, (value, key) => {
if (predicate(value, key, this)) {
super.set(key, value)
} else if (super.has(key)) {
super.remove(key)
}
})
}
_onRemove (items) {
forEach(items, (value, key) => {
if (super.has(key)) {
super.remove(key)
}
})
}
}