@syncthetic/emitter v0.0.2
@syncthetic/emitter
An angular library to watch for event changes. Fire events when a defined event returns true
To get started, install the package
npm i @syncthetic/emitter
importing the emitter service
import { EmitService } from '@syncthetic/emitter'
constructor config, of course...
constructor ( private emitter: EmitService, ... ) {}
Triggers and their options are configured in the following interface format
interface Trigger {
check: Function,
callback: Function
options?: TriggerOptions
}interface TriggerOptions {
originalValue?: any,
newValue?: any,
dataSet?: any
}To set up our event emitter, a few things need to be established.
You need a compare function, which will be run by the EmitService defined as the Trigger.check value. The function should return a boolean based value. When this function return true, the Trigger.callback function will be called. If Trigger.options exist and are defined, it will be passed into the check and callback functions.
Let's see some code...
In this exmaple, I have designed a small snippet, which runs on an array of numbers to detect if a change occured at a specific index.
numbers_differ ( options ) {
console.log('would compare', options.originalValue, ' with ', options.dataSet.data[1])
options.newValue = options.dataSet.data[1]
return options.originalValue !== options.dataSet.data[1]
}
show_number_differs ( options ) {
alert( options.originalValue + ' does not equal ' + options.newValue )
}
this.emit.add_trigger({
check: this.numbers_differ,
callback: this.show_number_differs,
options: { originalValue: this.data.data[1], dataSet: this.data }
})
// starts the EmitterService to check for triggers
this.emit.trigger_loop()Here's what we did
1. We initialized a trigger to watch the the array (this.data.data[1]) value at index 1
2. We pass in the options, to our check function so we can see the originalValue and dataSet (the array to monitor), and to be able to set the newValue from the callback function.
Here is the data.service.ts file generating our data.data list.
export class DataService {
data: Number[] = []
constructor() {
this.start_randomizing()
this.show_data()
}
generate_data () {
console.log('generating data')
const new_data = []
for (let i = 1; i < 10; i++) {
const n = Math.floor(Math.random()*(999-100+1)+100)
new_data.push(n)
}
this.data = new_data
}
start_randomizing () {
setInterval(this.generate_data.bind(this), 3000)
}
}