6

I am an experienced C++ developer but new to JavaScript. I want to write an ES6 JavaScript class that maintains state.

How do I tell when state has changed?

I can think of two ways to do this. One way is to inspect an instance of the class to see if it is "dirty" since the last time it was marked "clean". I.e. mark an instance object as clean and changing any data member of the class marks it as dirty. Or be able to compare two instances of the same class. If an incoming state does not equal a known state then state has changed. I know this is not built into JavaScript.

What is the best way to do this in JavaScript? I am working in Typescript if it makes a difference.

Nathan Tuggy
3431 gold badge6 silver badges14 bronze badges
asked Jan 20, 2016 at 16:37
2
  • 3
    I am working in Typescript if it makes a difference. -- It does. Typescript has Properties, which means that you can write Setters that set a boolean dirty field, and expose a property that reads that dirty field. Commented Jan 20, 2016 at 16:46
  • @RobertHarvey: Native javascript (es5+) also directly supports custom properties. However, I would favor Typescript properties, since Typescript properties have tighter syntax. See stackoverflow.com/a/12850536/18192 for an illustration of both. Commented Jan 20, 2016 at 18:07

2 Answers 2

1

Based on comments, here's a dirty-bit implementation that should work:

class Dirtyable {
 private _isDirty:Boolean = false;
 get isDirty():Boolean {
 return _isDirty;
 }
 private _example:String;
 get example():String {
 return _example;
 }
 set example(val):String {
 if (val !== _example) _isDirty = true;
 _example = val;
 }
}
0

Would this be an acceptable solution if the number of data members or fields of the class is large?

export class State {
 private _dirty: boolean = false;
 private _data1: string = '';
 private _data2: number = 0;
 constructor( d1: string, d2: number ) {
 this._data1 = d1;
 this._data2 = d2;
 }
 get dirty() {
 return this._dirty;
 }
 set dirty( value: boolean ) {
 this._dirty = value;
 }
 set( field: string, value: any ) {
 var theField: any = this[field];
 if ( theField != undefined ) {
 this[field] = value;
 this._dirty = true;
 }
 else {
 console.log( 'Field "' + field + '" is not defined' );
 throw 'Field "' + field + '" is not defined';
 }
 }
}

Example usage:

var rs1: State = new State( "one", 1 );
var isDirty = rs1.dirty;
rs1.set( '_data1', "two" );
isDirty = rs1.dirty;
rs1.set( 'blah', "two" );
answered Jan 20, 2016 at 20:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.