{"id":22231323,"url":"https://github.com/maksims/mr-observer","last_synced_at":"2025-07-27T20:32:08.998Z","repository":{"id":57303794,"uuid":"332794133","full_name":"Maksims/mr-Observer","owner":"Maksims","description":"An observer is a wrapper over JSON data, that provides an interface to know when data is changed, with a focus on performance and memory efficiency.","archived":false,"fork":false,"pushed_at":"2021-08-27T11:03:10.000Z","size":160,"stargazers_count":23,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-11-22T17:49:15.421Z","etag":null,"topics":["data-centric","data-proxy","json-proxy","object-proxying","observer"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Maksims.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-01-25T15:34:57.000Z","updated_at":"2022-09-02T15:01:30.000Z","dependencies_parsed_at":"2022-08-24T17:10:21.674Z","dependency_job_id":null,"html_url":"https://github.com/Maksims/mr-Observer","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maksims%2Fmr-Observer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maksims%2Fmr-Observer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maksims%2Fmr-Observer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maksims%2Fmr-Observer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Maksims","download_url":"https://codeload.github.com/Maksims/mr-Observer/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227832617,"owners_count":17826379,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-centric","data-proxy","json-proxy","object-proxying","observer"],"created_at":"2024-12-03T01:23:34.192Z","updated_at":"2024-12-03T01:23:36.136Z","avatar_url":"https://github.com/Maksims.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# mr-Observer\n\nObserver is a wrapper over JSON data, that provides an interface to know when data is changed, with a focus on performance and memory efficiency.\n\nFor data-centric design, this provides a modular and robust pattern for applications with various data-dependent parts: ui, real-time render, history undo/redo, real-time collaboration, and more. This pattern has been used for years in [PlayCanvas Editor](https://playcanvas.com/) providing fast iteration and ease of development in a complex environment.\n\nThis library it has two build targets: ES5 (ECMA2009) and ES8+ (modern JS), to maximize [browser support](#Browser) without sacraficing benefits of modern JS for majority of users. And can be used with ECMA Modules in Node.js.\n\n[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](LICENSE)\n\n\n## :rocket: Install\n\n\n#### Node.js\n\nInstall:\n```bash\nnpm install mr-observer\n```\n\nIn Node.js:\n```js\nimport Observer from 'mr-observer';\n```\n\n\n#### Browser\n\n```html\n\u003cscript type='module' src='mr-observer.min.js'\u003e\u003c/script\u003e\n\u003cscript nomodule src='mr-observer.es5.min.js'\u003e\u003c/script\u003e\n```\nUse built files from `dist` directory for browser. It will load ES8+ version if it is supported ([~94%](https://caniuse.com/?search=ES8)), otherwise it will load ES5 (ECMA2009) version that supports pretty much [every](https://caniuse.com/?search=ES5) platform.\n\n#### CDN ([jsDelivr](https://www.jsdelivr.com/))\n\nYou can use a public CDN for the library:\n\nES8+ module: https://cdn.jsdelivr.net/npm/mr-observer@1.1/dist/mr-observer.min.js  \nES5 version: https://cdn.jsdelivr.net/npm/mr-observer@1.1/dist/mr-observer.es5.min.js\n\n#### Example\n\n```js\nlet earth = new Observer({ age: 4.543, population: 7.594 });\n\nearth.on('population:set', function (path, value) {\n    element.textContent = value;\n});\n\nearth.set('population', 7.595);\n// fires \"population:set\" event\n```\n\n\n## :scroll: [API Documentation](API.md)\n\n## Usage\n\n#### Creating:\n\nCreating Observer (object):\n```js\nlet obj = new Observer({ position: { x: 4, y: 2 } });\n```\n\nCreating Observer (array):\n```js\nlet planets = new Observer([ 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune' ]);\n```\n\n#### Get:\n\nData provided to Observer should not be modified by application logic, it is not cloned either as it is a choice for a developer. Accessing data is possible through `.data` property or `get` method. Where `get` method is more safe approach, as it will handle undefined paths well:\n\n```js\nlet obj = new Observer({ position: { x: 4, y: 2 } });\nconsole.log(obj.get('position.x')); // 4\nconsole.log(obj.get('position.z')); // undefined\nconsole.log(obj.get('hello.world')); // undefined\n```\n\n```js\nconsole.log(planets.get(8)); // undefined, sorry Pluto\n```\n\nReturned values should NOT be modified by an application logic:\n```js\nlet obj = new Observer({ position: { x: 4, y: 2 } });\nlet position = obj.get('position');\nposition.z = 10; // not good\nobj.data.position.z = 10; // not good\nobj.set('position.z', 10); // good\n```\n\n#### Set:\n\nSet is used to change data, which can fire \"set\" and \"unset\" events.\n\nBy specific path:\n```js\nobj.set('position.y', 64);\n```\n\nSet root of the data:\n```js\nobj.set({ hello: 'world' });\n```\n\nIf root is an array, index can be used:\n```js\nplanets.set(2, 'Earth');\n```\n\nSet will not create missing objects along the path:\n```js\nlet obj = new Observer({ });\nobj.set('hello.world', true);\n// `hello` is undefined, so this will not change data\n```\n\nSet can fire \"unset\" events:\n```js\nlet obj = new Observer({ position: { x: 4, y: 2 } });\n\n// this will trigger twice: `position.x` and `position.y`\nobj.on('unset', function (path) {\n    console.log(`\"${path.join('.')}\" has been unset`);\n});\n\nobj.set('position', { z: 64 });\n```\n\n\n#### Patch:\n\nPatch is used to partially update data, it will not unset values if they are missing in provided data. But can still trigger \"unset\" event when object is replaced with non-object value. If patching an array, `insert` event can be triggered when new values added.\n\nIt can be used same way as `set` method.\n\n```js\nlet obj = new Observer({ position: { x: 4, y: 2 } });\nobj.patch('position', { z: 64 });\n// data now is: { position: { x: 4, y: 2, z: 64 } };\n```\n\nCase where \"unset\" event can still occur:\n```js\nlet obj = new Observer({ position: { x: 4, y: 2 } });\n\n// this will trigger twice: `position.x` and `position.y`\nobj.on('unset', function (path) {\n    console.log(`\"${path.join('.')}\" has been unset`);\n});\n\nobj.patch('position', 64);\n// data now is: { position: 64 };\n```\n\n\n#### Unset:\n\nBy specific path:\n```js\nobj.unset('position.y');\n```\n\nReset root to an empty object:\n```js\nobj.unset();\n```\n\nIt is possible to clear (sets to an empty object) an observer without firing \"unset\" events, this will also unsubscribe all events:\n```js\nobj.clear();\n```\n\n\n#### Insert:\n\nWhen working with arrays, insert, move and remove methods to be used for better control over data.\n\nInsert to an array:\n```js\nconst planets = new Observer({\n    earth: {\n        satellites: [ ]\n    }\n});\nplanets.insert('earth.satellites', 'moon');\n```\n\nObserver as an array:\n```js\nconst primes = new Observer([ 2, 5, 7 ]);\nprimes.insert('', 11); // inserts to the end\n```\n\nInsert at a specific index:\n```js\nconst primes = new Observer([ 2, 5, 7 ]);\n// we forgot prime number 3 which should be second in a list\nprimes.insert('', 3, 1);\n```\n\nUsing negative index to insert from the end:\n```js\nlet planets = new Observer([ 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'uranus', 'neptune' ]);\n// we forgot saturn!\n// insert to the third index from the end\nplanets.insert('', 'saturn', -3);\n```\n\n\n#### Move:\nMoving items within array. It will trigger `move` event for affected items first, and then for the moved one.\n\n```js\nlet planets = new Observer([ 'earth', 'mercury', 'venus', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune' ]);\n// earth should be third!\n// move it from index 0 to index 2\nplanets.move('', 0, 2);\n```\n\nMove from the end to the beginning:\n```js\nitems.move('', -1, 0);\n```\n\n\n#### Remove:\nRemoving items can trigger `move` event for affected items, and then for the removed one will trigger `remove` event.\n\nRemove from the end:\n```js\nlet planets = new Observer([ 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto' ]);\n// Sorry pluto!\nplanets.remove('', -1);\n```\n\nRemove at a specific index:\n```js\nconst primes = new Observer([ 2, 3, 4, 5, 7, 11 ]);\n// 4 is not a prime!\nprimes.remove('', 2);\n```\n\n\n#### Subscribing to changes:\n\nThis library is using [mr-EventEmitter](https://github.com/Maksims/mr-EventEmitter/) for events management.\n\nSet event by a specific path\n```js\nlet obj = new Observer({ });\n\nobj.on('hello:set', function (path, value) {\n    console.log(`\"hello\" has been changed to \"${value}\"`);\n});\n\n// this will fire \"hello:set\" event\nobj.set('hello', 'world');\n```\n\nSet event without path (matches any set):\n```js\nlet obj = new Observer({ });\n\n// this will be executed 3 times\n// with these paths: 'position.x', 'position.y', 'position'\nobj.on('set', function (path, value) {\n    console.log(`\"${path.join('.')}\" has been changed to \"${value}\"`);\n});\n\nobj.set('position', { x: 4, y: 2 });\n```\n\nSet event using wildcard notation:\n```js\nlet planets = new Observer({ });\n\n// it will match with any first level property name, where second level property name is `name`\nplanets.on('*.name:set', function (path, value) {\n    console.log(`Planet \"${path[0]}\" name has been changed to \"${value}\"`);\n});\n\nplanets.set('earth', { name: 'Earth' });\nplanets.set('mars', { name: 'Mars' });\n```\n\nSecond example:\n```js\nlet obj = new Observer({\n    position: { x: 0, y: 0, z: 0 }\n});\n\n// it will match path with `position` as first level property and any second level property name\nobj.on('position.*:set', function (path, value) {\n    console.log(`Axis \"${path[1]}\" has been changed to \"${value}\"`);\n});\n\nobj.patch('position', { x: 0, y: 4, z: 8 });\nobj.set('position.x', 32);\n```\n\nSingle trigger of change:\n```js\nlet obj = new Observer({ });\n\n// will trigger only once\nobj.once('hello:set', function (path, value) {\n    console.log(`\"hello\" has been changed to \"${value}\"`);\n});\n\n// both will fire \"hello:set\" event\nobj.set('hello', 'world');\nobj.set('hello', 'space');\n```\n\nUnset event is similar to Set event, with path or without:\n```js\nlet obj = new Observer({ hello: 'world' });\n\nobj.on('hello:unset', function (path, valueOld) {\n    console.log(`\"hello\" has been unset`);\n});\n\n// this will fire \"hello:unset\" event\nobj.unset('hello');\n```\n\nArray events: `insert`, `move` and `remove` do not include index in a path:\n```js\nlet obj = new Observer({\n    planets: [ 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto' ]\n});\n\nobj.on('planets:remove', function(path, value, index) {\n    // path is [ 'planets' ]\n    console.log(`\"${value}\" has been removed from ${path.join('.')} at index ${index}`);\n});\n\n// Sorry pluto!\nobj.remove('planets', -1);\n```\n\nSubscribe to `insert` events on array:\n```js\nlet obj = new Observer({\n    planets: [ 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune' ]\n});\n\nobj.on('planets:insert', function(path, value, index) {\n    console.log(`\"${value}\" has been added to ${path.join('.')} at index ${index}`);\n});\n\nobj.insert('planets', 'planet nine');\n```\n\nValues and objects provided in events are actual for the duration of the event, and should not be stored or modified (if storing is desired then it should be cloned):\n```js\nlet obj = new Observer({ });\n\nlet position = null;\nobj.on('position:set', function (path, value) {\n    value.z = 64; // not good\n    position = value; // not good\n});\n\nobj.set('position', { x: 4, y: 2 });\n```\n\n\n#### Removing events:\n\nRemove event by [EventHandler](https://github.com/Maksims/mr-EventEmitter/blob/main/API.md#EventHandler):\n```js\nlet obj = new Observer({ hello: 'world' });\n\nlet evt = obj.on('hello:set', function (path, value) {\n    console.log(`hello ${value}`);\n});\n\nobj.set('hello', 'earth');\nobj.set('hello', 'space');\nevt.off(); // remove event\nobj.set('hello', 'another dimension'); // this will not be logged\n```\n\nIt is possible to remove all events, by specific path or using regular expression. For more details refer to [EventEmitter API](https://github.com/Maksims/mr-EventEmitter/blob/main/API.md)\n\n## Building\n\nBuilds single file into two ES5 and ES8+ versions using Babel and Terser.  \nSource file: `src/index.js`  \nBuilt versions ES5 (`dist/mr-observer.es5.min.js`) and ES8+ (`dist/mr-observer.min.js`):\n\n```bash\nnpm install\nnpm run build\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaksims%2Fmr-observer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaksims%2Fmr-observer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaksims%2Fmr-observer/lists"}