Design Pattern To Check If A Javascript Object Has Changed
Solution 1:
Here is a function down below that will return an array of changed objects when supplied with an old array of objects and a new array of objects:
getChanges = function(oldArray, newArray) {
var changes, i, item, j, len;
if (JSON.stringify(oldArray) === JSON.stringify(newArray)) {
returnfalse;
}
changes = [];
for (i = j = 0, len = newArray.length; j < len; i = ++j) {
item = newArray[i];
if (JSON.stringify(item) !== JSON.stringify(oldArray[i])) {
changes.push(item);
}
}
return changes;
};
For Example:
var older = [{name:'test01', age:10},{name:'test02', age:20},{name:'test03', age:30}]
var newer = [{name:'test01', age:10},{name:'test02', age:20},{name:'test03', age:20}]
getChanges(older, newer)
(Notice test03's age is now 20) Will return
[{name:'test03', age:20}]
You would simply have to export the full list of edited values client side, compare it with the old list, and then send the list of changes off to the server.
Hope this helps!
Solution 2:
Here are a few ideas.
Use a framework. You spoke of Angular.
Use Proxies, though Internet Explorer has no support for it.
Instead of using classic properties, maybe use
Object.defineProperty
's set/get to achieve some kind of change tracking.Use getter/setting functions to store data instead of properties:
getName()
andsetName()
for example. Though this the older way of doing whatdefineProperty
now does.Whenever you bind your data to your form elements, set a special property that indicates if the property has changed. Something like
__hasChanged
. Set to true if any property on the object changes.The old school bruteforce way: keep your original list of data that came from the server, deep copy it into another list, bind your form controls to the new list, then when the user clicks submit, compare the objects in the original list to the objects in the new list, plucking out the changed ones as you go. Probably the easiest, but not necessarily the cleanest.
A different take on #6: Attach a special property to each object that always returns the original version of the object:
var myData = [{name: "Larry", age: 47}];
var dataWithCopyOfSelf = myData.map(function(data) {
Object.assign({}, data, { original: data });
});
// now bind your form to dataWithCopyOfSelf.
Of course, this solution assumes a few things: (1) that your objects are flat and simple since Object.assign() doesn't deep copy, (2) that your original data set will never be changed, and (3) that nothing ever touches the contents of original
.
There are a multitude of solutions out there.
Solution 3:
With ES6 we can use Proxy
to accomplish this task: intercept an Object write, and mark it as dirty.
Proxy allows to create a handler Object that can trap, manipulate, and than forward changes to the original target Object, basically allowing to reconfigure its behavior. The trap we're going to adopt to intercept Object writes is the handler set().
At this point we can add a non-enumerable propertyflag like i.e: _isDirty
using Object.defineProperty() to mark our Object as modified, dirty.
When using traps (in our case the handler's set()
) no changes are applied nor reflected to the Objects, therefore we need to forward the argument values to the target Object using Reflect.set().
Finally, to retrieve the modified objects, filter()
the Array with our proxy Objects in search of those having its own Property"_isDirty"
.
// From server:const dataOrg = [
{id:1, name:'a', age:10},
{id:2, name:'b', age:20},
{id:3, name:'c', age:30}
];
// Mirror data from server to observable Proxies:const data = dataOrg.map(ob =>newProxy(ob, {
set() {
Object.defineProperty(ob, "_isDirty", {value: true}); // FlagreturnReflect.set(...arguments); // Forward trapped args to ob
}
}));
// From now on, use proxied data. Let's change some values:
data[0].name = "Lorem";
data[0].age = 42;
data[2].age = 31;
// Collect modified dataconst dataMod = data.filter(ob => ob.hasOwnProperty("_isDirty"));
// Test what we're about to send back to server:console.log(JSON.stringify(dataMod, null, 2));
Without using .defineProperty()
If for some reason you don't feel comfortable into tapping into the original object adding extra properties as flags, you could instead populate immediately
the dataMod
(array with modified Objects) with references:
const dataOrg = [
{id:1, name:'a', age:10},
{id:2, name:'b', age:20},
{id:3, name:'c', age:30}
];
// Prepare array to hold references to the modified Objectsconst dataMod = [];
const data = dataOrg.map(ob =>newProxy(ob, {
set() {
if (dataMod.indexOf(ob) < 0) dataMod.push(ob); // Push referencereturnReflect.set(...arguments);
}
}));
data[0].name = "Lorem";
data[0].age = 42;
data[2].age = 31;
console.log(JSON.stringify(dataMod, null, 2));
Solution 4:
Without having to get fancy with prototype properties you could simply store them in another array whenever your form control element detects a change
Something along the lines of:
var modified = [];
data.forEach(function(item){
var domNode = // whatever you use to match data to form control element
domNode.addEventListener('input',function(){
if(modified.indexOf(item) === -1){
modified.push(item);
}
});
});
Then send the modified
array to server when it's time to save
Solution 5:
Why not use Ember.js observable properties ? You can use the Ember.observer function to get and set changes in your data.
Ember.Object.extend({
valueObserver: Ember.observer('value', function(sender, key, value, rev) {
// Executes whenever the "value" property changes// See the addObserver method for more information about the callback arguments
})
});
The Ember.object actually does a lot of heavy lifting for you.
Once you define your object, add an observer like so:
object.addObserver('propertyKey', targetObject, targetAction)
Post a Comment for "Design Pattern To Check If A Javascript Object Has Changed"