How to Check If an Object Has Changed

Design pattern to check if a JavaScript object has changed

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)) {
return false;
}
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!

Check if an object has changed

What you are trying to do?

You are trying to compare object with itself, after some chain of "unknown" operations to check if the object has changed. If this is true, there are some logical points to observe. At first, if you want to compare object with itself, you've got only two options:

  1. Remember the whole object state (for example hash, or just copy whole object)
  2. Track changes over time

There is no other logical approach. Comparing memory allocations, real objects, copying objects, comparing hashes, is all in point one. Tracking changes, saving changes inside object, remembering meantime operations, inside point 2.

So in my opinion this question is sort of backing up data questions. In that case there are many, many solutions but none of them are hardcoded inside php as far as I'm concerned. Why?


The answer is simple. PHP guys have got the same problems you've got :). Because if this would be hardocded inside php, then php should run / use one of those mechanisms (1) or (2).

In that case every object that you create, and every operation you made should be written somewhere to remember every state / object / something and use them for comparison in the future.

While you need this solution, almost ~100% of websites don't. So hardcoding this inside php would made ~100% of websites work slower and your work faster ;).


PHP hypothetical solution?

The only solution (maybe built in php in the future) I can think of is making some kind of php config flag: track objects, and only if this flag is true, then run all the php mechanisms of tracking objects states. But this also mean a huge performance gap. As all the ifs (if tracking, if tracking, if tracking) are also procesor and memory time consuming.

There is also a problem, what to compare? You need to compare object with same object, but... Few minutes ago? Few operations ago? No... You must point exactly one place in code, and then point second place in code and compare object in those two places. So hypothetical auto tracking is... Kind of powerless, as there is no "key" in the object state ofer time array. I mean, even if you got magic_object_comparer function, what it should look like?

<?php

function magic_object_comparer() {} // Arguments??
function magic_object_comparer($object_before, $object_after) {} // you must save object_before somewhere...??
function magic_object_comparer($object, $miliseconds) {} // How many miliseconds?
function magic_object_comparer($object, $operations) {} // How many operations? Which operations?


magic_comparer_start($object);
// ... Few operations...
$boolean = magic_comparer_compare_from start($object);
// Same as own implementation...
?>

Sadly, you are left with own implementation...

After all, I would propose to implement some kind of own mechanism for that, and remember to use it only there, where you need it. As this mechanism will for sure be time and memory consuming. So think carefully:

  1. Which objects you want to compare. Why?
  2. When you want to compare them?
  3. Does all changes need to be compared?
  4. What is the easiest way of saving those states changes?

And after all of that, try to implement it. I see that you've got a huge php knowledge, so I'm pretty sure that you will figure out something. There are also many comments, and possible ideas in this question and discussion.


But after all maybe I explained a little why, there is no build in solution, and why there should not be one in the future... :).


UPDATE

Take a look here: http://www.fluffycat.com/PHP-Design-Patterns/. This is a great resource about php patterns. You should take a look at adapter, decorator and observer patterns, for possible elegant object oriented solutions.

Checking if contained object has changed

The answer is in your question. Use a property.

class Part:
_size = 0
assembly = None

@property
def part_size(self):
return self._size

@part_size.setter
def part_size(self, value):
self._size = value
if self.assembly: # only notify if an Assembly is set
self.assembly.update()

def set_assembly(self, assembly):
self.assembly = assembly

def __init__(self, size):
self.part_size = size

class Assembly:
def __init__(self, *parts):
self.parts = list(parts) # `parts` are all Part() objects
for part in self.parts:
part.set_assembly(self) # reference to self needed to notify changes
self.update()

def update(self):
self.assy_size = 0
for each in self.parts:
self.assy_size += each.part_size

In this version of Assembly the constructor sets a reference on the Part to itself. This way it can update the assembly when the part_size changes. Use it as the example in your question.

>>>x = Part(1)
>>>y = Part(1)
>>>z = Part(1)
>>>u = Assembly(x, y, z)
>>>u.assy_size
3
>>>u[0].part_size = 4
>>>u.assy_size
6

How to detect if an object variable has been changed?

var fence= {
set x1(){
alert('change');
this.rebuild();
},
rebuild: function(){}
}

Also

function Fence(val){
var value = val;

this.__defineGetter__("x1", function(){
return value;
});

this.__defineSetter__("x1", function(val){
alert('change');
this.rebuild();
});
this.rebuild = function(){};
}
var fence = new Fence();

How to check if an object has changed?

How do you define "equality" (between old and new state)?

  • Are you comparing properties only or fields as well?
  • Are you only comparing public properties/fields?
  • Do you ever ignore any properties/fields (i.e. their modifications do not matter)?
  • How do you compare "atomic" types (e.g. are all string comparisons case-insensitive, or you need case-sensitive in some places as well).

If answers to these questions are general enough (i.e. you can devise a set of rules that apply to all of your objects), then you could theoretically accomplish what you want through reflection: The basic idea is to read all properties/fields of the "root" object, then store the "atomic" ones and recursively descend into the "non-atomic" ones (and repeat the whole process). Later, when you want to check if anything changed, you would repeat the recursive descent and compare the results with the stored values.

I'm not arguing this solution is particularly performant or even easy (you'd need to devise a robust naming convention for storing old values and be very careful about multi-threading), but it could potentially be general.

How to check if an object has changed property in deserialisation c#

You could iterate through the collections and compare the objects.

If you find a match, you update the corresponding object and if you don't you either add or remove it from the data-bound source collection.

You could perform the actual iterating on a background thread in order to keep the app responsive, but you will still need to add/remove items from the source collection back on the UI thread so doing this is probably pretty pointless from a performance perspective anyway.

How to detect when object value change?

You can pass the handler function to Proxy and you need to change values on proxies not on original object

var values ={Value1: 0, Value2:0};
let handler = { set: function whenChange(obj,prop,value) { obj[prop] = value console.log("The value of the object has changed!"); return true }}var checkObjectChange = new Proxy(values, handler);
console.log("The object values are: "+JSON.stringify(checkObjectChange))
$("#btn1").on("click", function() { checkObjectChange.Value1 = 1; console.log("Now the object values are: "+JSON.stringify(checkObjectChange));});
$("#btn2").on("click", function() { checkObjectChange.Value2 = 1; console.log("Now the object values are: "+JSON.stringify(checkObjectChange));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1">Change value 1</button><button id="btn2">Change value 2</button>


Related Topics



Leave a reply



Submit