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.

  • 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. – Robert Harvey Jan 20 '16 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. – Brian Jan 20 '16 at 18:07
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" );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.