Skip to content

Instantly share code, notes, and snippets.

@dr-dimitru
Created September 11, 2014 16:18
Show Gist options
  • Save dr-dimitru/a9037e3df006f33886eb to your computer and use it in GitHub Desktop.
Save dr-dimitru/a9037e3df006f33886eb to your computer and use it in GitHub Desktop.
Meteor defineReactiveProperty() method
/*
* @function
* @name Object.defineReactiveProperty
* @description define Reactive property:
* - set callback before Setter and Getter
* - set callback on Setter
* - set callback on Getter
*
* @param {object} target - Object on which we define a property
* @param {string} prop - Name of defining property
* @param {mix} value - Assigned value to newly created property
* @param {function} callback - callback function with two parameters:
* @param {string} prop - property name to be defined or modified
* @param {mix} currentValue - Current value of object's property
* @param {object} target - The object we working with
*
* @param {function} getCallback - Callback function on object's property Getter, with two parameters:
* @param {string} prop - property name to be defined or modified
* @param {mix} currentValue - Current value of object's property
*
* @param {function} setCallback - Callback function on object's property Setter, with two parameters:
* @param {string} prop - property name to be defined or modified
* @param {mix} currentValue - New (created || modified) value of object's property
*
*/
Object.defineReactiveProperty = function (target, prop, value, callback, getCallback, setCallback) {
var currentValue = (value) ? value : (target[prop]) ? target[prop] : ' ';
callback && callback(prop, currentValue, target);
Object.defineProperty(target, prop, {
get: function () {
if(getCallback){
return getCallback(prop, currentValue);
}else{
return currentValue;
}
},
set: function (newValue) {
if(JSON.stringify(newValue) !== JSON.stringify(currentValue)) {
currentValue = newValue;
setCallback && setCallback(prop, currentValue);
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment