2.2.0 • Published 3 months ago

@jalik/observer v2.2.0

Weekly downloads
36
License
MIT
Repository
github
Last release
3 months ago

@jalik/observer

GitHub package.json version Build Status GitHub last commit GitHub issues GitHub npm

Make anything observable.

Introduction

The Observer design pattern is a well known pattern to create reactive applications.
You can attach observers to a form text field, then when the text field value changes, all observers are notified of that change and thus can do something in response.

Features

  • Add event listeners
  • Remove event listeners
  • Emit events with arguments passed to listeners
  • Includes TypeScript declarations

Sandbox

Play with the lib here: https://codesandbox.io/s/jalik-observer-demo-de16gw?file=/src/index.js

Adding an event listener

import { Observer } from '@jalik/observer'

class Person {
  constructor (name) {
    this.name = name
    // Create the observer with current context
    this.observer = new Observer(this)
  }

  on (event, observer) {
    // Attach observer
    this.observer.on(event, observer)
  }

  say (words) {
    // Notify observers
    this.observer.emit('say', words, new Date())
  }
}

const karl = new Person('karl')

karl.on('say', function (words, date) {
  console.log(`${this.name} said: "${words}"`)
})
// this will show: karl said: "hello"
karl.say('hello')

Removing an event listener

import { Observer } from '@jalik/observer'

const listener = function () {
  console.log('double click detected')
  // This avoid the current function to be called
  // on the next "doubleClick" event notification.
  observer.off('doubleClick', listener)
}

const observer = new Observer()
observer.on('doubleClick', listener)

// This will call the doubleClickListener once.
observer.emit('doubleClick')

// This will not call the doubleClickListener
// since it has been detached in the previous call.
observer.emit('doubleClick')

Changelog

History of releases is in the changelog.

License

The code is released under the MIT License.

2.2.0

3 months ago

2.1.0

3 months ago

2.0.0

3 months ago

1.2.0

1 year ago

1.2.1

1 year ago

1.1.14

2 years ago

1.1.13

3 years ago

1.1.12

3 years ago

1.1.11

3 years ago

1.1.10

3 years ago

1.1.9

4 years ago

1.1.8

4 years ago

1.1.7

4 years ago

1.1.6

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.6

5 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago