It's a small js library to bind a variable to HTML elements..
Inspired from Svelte Store.
When it's called returns an object with four methods.
set
get
update
subscribe
import justBind from 'justbind';
const name = justBind('name'/*, initial value*/);
This immediately sets the value of name
to given value.
name.set('John');
This returns the current value of name
.
name.get(); //Returns 'John'
This is used to update the value of name
, it accepts a function that returns the new value. Current value is passed to the function.
name.update(value => value + ' Doe');
This accepts a callback function that is called whenever the value of name
changes. Either by calling set
or update
methods or via assigned inputs.
name.subscribe(value => console.log(value));
name.set('John');
// Console prints output:
// John
You can bind the value of name
to HTML elements. Whenever the value of name
changes, the value of the HTML element will be updated or if it's an input, the value of the input will be updated.
Values also will be updated when the content of the HTML element is changed, like if you type something in the input.
<script>
const name = justBind('name',"John");
</script>
<input type="text" bind="name">
- Custom attributes works but they aren't valid W3C standards.
- Event though they work, that doesn't mean you may not encounter with any problems.
- One option is you can use something like DTD - Attributes, or avoid this library all together.
- Probably there are better ways to achieve this.
- Stores can be initiated with persist option, either with localStorage or sessionStorage.
- I can consider changing
bind=
attribute todata-bind=
attribute. To make it W3C compliant. Bind
method: for binding to HTML Elements via function.- Web Components? Maybe a custom component can be placed.
MIT License
2023 @Siniradam