lsync

1.0.0 • Public • Published

LSync

LSync is a library that synchronizes variables between an object on your client and server, via a socket.io socket.

Including

From Node.JS:

npm i --save lsync
const lsync = require('lsync')

From the Browser:

First, download lsync.js to your project directory.

<script src="lsync.js"></script>

Initialization

LSync instances are initialized exactly the same on the client and server. They must be supplied a common identifier which is unique on that socket, and a connected Socket.IO socket to use.

let s = lsync('shared-name-between-client-and-server', socket)

Publishing

From an LSync instance, a new variable can be created using:

s.publish({ name: 'foo', value: 'bar' })

After publishing a variable, it can be used and changed by both the client and server - which will both keep its value in sync.

// On Node A:
s.foo // => 'bar'
s.foo = 'hello'

// On Node B:
s.foo // => 'hello'

Read-Only (One-Way) Values

If you wish to create a value which can only be updated by the node that originally published it, you can specify the readonly option:

// On Node A:
s.publish({ name: 'test', value: 'hello', readonly: true })

// On Node B:
s.test // => 'hello'
s.test = 'foo' // Won't work, it's read-only on this end!
s.test // => 'hello'

// On Node A:
s.test = 'foo'
s.test // => 'foo'

Syncing Objects

Unfortunately, LSync cannot automatically detect and sync changes to an Object's properties. To sync an object, call s.sync(name) after each change:

// On Node A:
s.publish({ name: 'object', value: { a: 10, b: 20 } })

// On Node B:
s.object.a = 20

// On Node A:
s.object.a // => 10

// On Node B:
s.sync('object')

// On Node A:
s.object.a // => 20

Change Bindings

If you want to be notified whenever a certain value is changed, the bind function can help:

// On Node A:
s.publish({ name: 'foo', value: 'hello' })
s.bind('foo', (newValue) => console.log(`new value: ${newValue}`))

// On Node B:
s.foo = 'world'

// On Node A:
// => new value: ${newValue}

bind takes the name of the property to listen for, and a callback. This callback will be called whenever the property's value is changed, and is given a single argument: the new value.

Testing LSync

To test out LSync, clone the repository, run npm i, and then use npm test to start the LSync server. Once the server is running, visit localhost:3000 and open your browser's developer console. The server will open a REPL similar to that of your browser, and an instance of LSync is available in the s object on both.

Readme

Keywords

none

Package Sidebar

Install

npm i lsync

Weekly Downloads

1

Version

1.0.0

License

MIT

Last publish

Collaborators

  • mctague