Data binding for 2 $

Data binding for 2 $
0.0 0

#1

$ Data-binding

I there, I just wanted to share my most recent code and get some ideas of other functionnalities to add.
It is a short code to bind object properties.

Say hello to the $ data-binder, a really short and expressive way to bind data between objects:

const obj = {
  a: 0,
  b: 0,
};
$(obj).b = $(obj).a;
obj.a = 42;
console.log(obj.b) // => 42

Can also set data from unique or multiple sources through a setter function, and also trigger functions on data changes:

const o1 = {
  a: 0,
  d: 0,
  deep: {
    deep2: 0,
  },
};
const o2 = {
  b: 0,
  c: 0,
  log: console.log,
};
const $o1 = $(o1);
const $o2 = $(o2);

const double = (v) => v * 2;
const product = (a, b, c) => a * b * c;

$o2.b = $o1.a;

$o2.log = $o1.a; // log 0
// or $.bind(o1.a).on(o2.log);

$o2.c = $(double, $o1.a);

$o1.deep.deep2 = $(product, $o1.a, $o1.d, 2.5);
// or $.setter(product, o1.a, o1.d, 2.5).on(o1.deep.deep2);

o1.a = 1; // log 1
console.log(o2.b, o2.c, o1.deep.deep2); // => 1, 2 = 2*1, 0 = 1*0*2.5
o1.d = 4;
console.log(o2.b, o2.c, o1.deep.deep2); // => 1, 2 = 2*1, 10 = 1*4*2.5
o1.a = 2; // log 2
console.log(o2.b, o2.c, o1.deep.deep2); // => 2, 4 = 2*2, 20 = 2*4*2.5

Pratical example :

Case converter :
Imagine you have for exemple a code generator. You define a variable name, but depending on the place you want to display it in camel case, upper caseā€¦ You could use $ this way :


const variable = {
  value: 42,
  name: "default",
  kamel: "",
  pascal: "",
  upper: "",
}
const $v = $(variable);

const Pascal = (name) => name.toLowerCase().split(" ").map((word) => word[0].toUpperCase() + word.sllice(1)).join("");
const Kamel = (name) => Pascal(name)[0].toLowerCase() + Pascal(name).slice(1);
const Upper = (name) => name.split(" ").join("_").toUpperCase();

$v.kamel = $(Kamel, $v.name);
$v.pascal= $(Pascal, $v.name);
$v.upper = $(Upper , $v.name);

variable.name = "Chuck Norris"; // => { pascal: "ChuckNorris", kamel: "chuckNorris", upper: "CHUCK_NORRIS"}

Github : https://github.com/MagicMixer/Data-binding