Skip to content

Instantly share code, notes, and snippets.

@ppraksa
Last active July 25, 2024 09:30
Show Gist options
  • Select an option

  • Save ppraksa/aade6f85e2499eef35080f908a87ed18 to your computer and use it in GitHub Desktop.

Select an option

Save ppraksa/aade6f85e2499eef35080f908a87ed18 to your computer and use it in GitHub Desktop.
// Implementation of observable value with cb function
function dandycode() {
var value = Array.prototype.slice.call(arguments)[0];
var dandy = {};
if (!(this instanceof dandycode)) {
return new dandycode(value);
}
this.value = value;
this.observables = [];
dandy = {
set: function (value) {
this.observables.forEach(fn => {
fn.call(this, this.value, value);
})
return this.value = value
},
get: function () {
return this.value
}
};
dandy = Object.assign(dandy, this);
return function () {
if (arguments[0] === 'observe'
&& typeof arguments[1] === 'function') {
this.observables.push(arguments[1]);
} else {
return arguments.length === 0 ? dandy.get() : dandy.set(arguments[0]);
}
}.bind(this);
}
var test = dandycode(20);
var myAge = dandycode(35);
myAge('observe', function(oldVal, newVal) {
console.log('Im older now', oldVal, newVal);
});
test('observe', function(oldVal, newVal) {
console.log('observer is fired', oldVal, newVal);
});
test('observe', function(oldVal, newVal) {
console.log('another observer which multiple new value', newVal * 2);
});
console.log(test());
console.log(test(33));
console.log(test());
console.log(test(25));
console.log(test(2));
console.log(test());
console.log(test(35));
console.log(test());
console.log(myAge());
console.log(myAge(36));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment