object observer – icaro

icaro

A smart and efficient javascript object observer, ideal for batching DOM updates ( ~1kb )

Installation

Via npm

$ npm i icaro -S

Script import

Via<script>

<script src='path/to/icaro.js'></script>

Via ES2015 modules

import icaro from 'icaro'

Via commonjs

const icaro = require('icaro')

Demos

Performance

icarois really fast compared to the other reactive libs because it smartly throttles all the state changes.

Usage

icarowill let you listen to all the changes happening in a javascript object or array, grouping them efficiently, and optimizing the performance of your listeners.

const obj = icaro({})

// the variable "changes" here is a Map and the function is async
obj.listen(function(changes) {
  console.log(changes.get('foo')) // 'hi'
  console.log(changes.get('bar')) // 'there'
  console.log(changes.get('baz')) // 'dude'

  // kill all the listeners
  obj.unlisten()
})

obj.foo = 'hi'
obj.bar = 'there'
obj.baz = 'dude'

icarowill also let you listen to nested objects and all the non primitive properties added to anicaroobject will be automatically converted intoicaroobservable objects.

const obj = icaro({})

// listen only the changes happening on the root object
obj.listen(function(changes) {
})

obj.nested = {

}

obj.nested.listen(function(changes) {
  // listen only the changes of obj.nested
})

obj.nested.someVal = 'hello'

icarois able also to listen changes in arrays. Any change to the items indexes will dispatch events.

// Here a bit of hardcore async stuff

const arr = icaro([])

// here you will get the index of the items added or who changed their position
arr.listen(function(changes) {
  console.log(changes.get('0')) // 'foo'
  console.log(changes.get('1')) // 'bar'
  // kill all the listeners this included
  arr.unlisten()

  // add a brand new listener recursively.. why not?
  arr.listen(function(changes) {
    // the change was triggered by a 'reverse' and all indexes were updated
    console.log(changes.get('0')) // 'bar'
    console.log(changes.get('1')) // 'foo'
  })

  // update all the indexes
  arr.reverse()
})

// initial dispatch
arr.push('foo')
arr.push('bar')

You can also avoid unsubscribing (“unlisten”) becauseicarowill automatically remove event listeners when the object is about to be garbage collected.

API

Anyicarocall will return a Proxy with the following api methods

icaro.listen(callback)

Listen any object or array calling the callback function asynchronously grouping all the contiguous changes via setImmediate

@returns self

icaro.unlisten(callback|null)

Unsubscribing a callback previously subscribed to the object, if no callback is provided all the previous subscriptions will be cleared

@returns self

icaro.toJSON()

Return all data contained in anicaroProxy as JSON object

@returns Object

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:object observer – icaro