Skip to content

Latest commit

 

History

History
326 lines (245 loc) · 9.61 KB

README.md

File metadata and controls

326 lines (245 loc) · 9.61 KB

way.js

Simple, lightweight, persistent, framework-agnostic two-way databinding Javascript library (with no to little JS code to write).

Demo
Codepen
jsFiddle

Follow us on Twitter: @way_js

Quick start

Declare an HTML element with some tags.

  <form way-data="myFormData" way-persistent="true">
  	<input type="text" name="name">
  	<input type="text" name="age">
  	<input type="text" name="gender">
  </form>

  Name: <span way-data="myFormData.name"></span>

Boom. Now every change in the form will be stored in-memory. The bound span's html will be changed on the fly. And the bound data will be persistent, meaning your HTML will be populated with your data on page reloads.

Enough talk, see it in action.

Installation

Step 1: Include the bundled library to your page.

<script src="/way.bundle.min.js"></script>

Step 2: There is no step 2. You are good to go.

Note: The bundled version contains the required dependencies (listed below). Feel free to include them separately.

<script src="/vendor/jquery.js"></script>
<script src="/vendor/underscore.js"></script>
<script src="/vendor/underscore.json.js"></script>
<script src="/vendor/form2js.js"></script>
<script src="/vendor/js2form.js"></script>
<script src="/way.min.js"></script>

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to way-, as in way-data="". Set these options to the elements that have to be bound.

Name Type Default Description
data string null Allows to define the dot separated path where the data will be stored. Can include arrays. When used on a form, a json variable made of all the included inputs with a [name] attribute will be created and stored in the specified storage. Pass the "__all__" path to access all way.js' data.
default string null A link to a default data to set on an element, in case there is no bound value.
persistent boolean true Allows to store the data to localStorage everytime the bound data changes.
readonly boolean false Prevents the element changes from resetting the bound value.
writeonly Boolean false Prevents the element from getting changed when the bound value changes.
json boolean false Returns pretty-printed json data to its DOM element.
html boolean false Declares whether the data attributed to an element should be parsed as HTML or not.
pick array null A comma separated list of values to pick (in forms only) to sync with the storage. By default, all form inputs are synced.
omit array null A comma separated list of values (in forms only) to not sync with the storage. By default, no form input is omitted.

Some examples:

<form way-data="some.form" way-pick="some,properties,that,can.be.nested">
<form way-data="some.form" way-omit="dont,want.those">
<img way-data="some.image" way-default="http://upload.wikimedia.org/wikipedia/en/a/a6/Bender_Rodriguez.png">
<pre way-data="some.json" way-json="true"></pre>

Helper classes

For images only
way.js adds classes to your DOM elements to easily detect load / error / success statuses with the data they get passed.

Class Description
way-loading When an image is getting downloaded to a DOM element
way-error When no image is returned from the URL provided
way-success When... Well, you got it.
way.set("image.url", "somethingThatsNotAnImageURL");
<img way-data="image.url">
<!-- Gets a class ".way-error" attributed -->

Methods

Everything should be done for you from the HTML tags. But if necessary, you can also use helper functions to interact with your stored data and DOM elements.

Notes:

  • [element] refers to the jQuery selector of a DOM element
  • [options] is optional. By default, options are read from the HTML tags of the elements. But you can overwrite them, by passing this parameter.

DOM methods

way.dom(element).toStorage(options)
Stores the element's value to the in-store memory.

way.dom("#someForm").toStorage()

way.dom(element).fromStorage(options)
Sets the element's value from the stored one.

way.dom("#someForm").fromStorage()

way.dom(element).toJSON(options)
Returns a JSON with the parsed data of the input (particularly handy for forms).

way.dom("#someForm").toJSON()

>> {
		its: "values",
		serialized: {
			in: "a json"
		}
	}

way.dom(element).fromJSON(data, options)
Sets the element's value from any data (in json).

way.dom("#someForm").fromJSON({name:"John Doe"})

way.dom(element).getValue()
Returns a structured JSON containing the value of the DOM element.

way.dom("#someForm").getValue()

way.dom(element).setValue(value, options)
Sets the element's value from any data (in json).

way.dom("#someForm").setValue({name:"John Doe"})

way.dom(element).setDefault(force)
Sets the default value of an element. By default, only the DOM element gets its value set to the default value. Its bound value in the datastore in unchanged. Pass a [force] parameter if you need to force setting in-memory value of this data to the element's default value.

way.dom("#someForm").setDefault()

way.setDefaults(force)
Sets all the default values of bound DOM elements.

way.setDefaults()

way.dom(element).getOptions()
Returns the list of the ["way-"] options attributed to a DOM element.

way.dom("#someForm").getOptions()

Data methods

way.get(selector)
Returns the value of the data stored under a given pathname.

way.get("some.path");
>> "bonjour"

way.set(selector, value, options)
Saves the data in memory under the specified pathname.

way.set("some.path", "bonjour!");

way.remove(selector, options)
Removes the data stored under a given pathname.

way.remove("some.path");
way.get("some.path");
>> undefined

way.clear(options)
Clears all the data

way.clear();
way.get();
>> {}

localStorage methods

way.backup()
Stores the data saved in way.js' datastore to localStorage.

way.backup();

way.restore()
Restores the data saved in localStorage. Called on $(document).ready by default (can be changed with global options).

way.restore();

Binding methods

way.registerBindings()
Triggers a scan of the DOM to find and save the elements with the [way-data] attribute, that will be bound with some data.

way.registerBindings()

way.updateBindings(selector)
Sets the value of all the DOM elements binded to a data selector with their values in way.js' datastore. If omitted, all (excluding write-only's and omitted) DOM elements with a "way-data=" attribute will be refreshed.

way.updateBindings("formData.name")

Watcher methods

way.watch(selector, callback[value])
Watches changes of a given value.

way.watch("some.data", function(value) {
	console.log("Data has been updated to value: " + value);
});

way.watchAll(callback[selector, value])
Watches all changes in way.js' datastore.

way.watchAll(function(selector, value) {
	console.log("The data " + selector + "has been changed.", value);
});

Global options

way.options.persistent (Boolean)
Sets whether or not data will be saved to / restored from localStorage (true by default).

way.options.persistent = true

way.options.timeoutInput (Number)
Number of milliseconds of the timeout between keypresses on bound elements to store their values to the datastore (50 by default).

way.options.persistent = 50

way.options.timeoutDOM (Number)
Number of milliseconds of the timeout between scans of the DOM to list bound elements on each DOM change (500 by default).

way.options.persistent = 500

To do

  • document a bit more the code
  • test
  • enjoy

Integrations

  • [Meteor] To be coming

Contribute

  • Fork & pull request.
  • If you planning add some feature please create issue before.

Otherwise changes will be rejected.

Credits

form2js' author

Licence

The MIT License

Copyright (c) 2011 Gwendall Esnault [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.