Store state of a JavaScript Object

做~自己de王妃 提交于 2019-12-04 07:56:08
marionebl

The issue you are running into is that in js objects are passed by reference. This means that all changes performed on your object will apply to your obj.savedItem property.

Fix: Store a deep clone into obj.savedItem

 this.storeState = function() {
     this.savedItem = _.cloneDeep(this); // or _.clone(this, true);
 }

cloneDeep is a lodash method, most js libs supply one of their own, e.g. jQuery's $.extend, etc.

You could easily roll your own deep clone function, look up the options on this thread.

A complete example with jQuery:

function SavedFeature() {
    this.savedItem;

    this.clone = function() {
       return $.extend(true, {}, this);
    },

    this.storeState = function() {
        this.savedItem = this.clone();
    }
}

Doing it this way allows you adapt to different environments by changing your clone method as it is facading the used library method.

There are dozens of ways how to implement it. I will do just simple one. saving property. Take into account if you want to save entire object you need to do deep copy of the object.

this is your feature:

function SavedFeature() {
        this.savedItem = {'isNew': true};
        this.stateMachine = new StateMachine();
}

this is some kind of state machine:

function StateMachine () {
      var state = { 'isNew' : null};
      function set(newState) {
         state.isNew = newState.isNew;
      }
      function get() {
         return state.isNew;
      }
      return {
      get : get,
      set : set
      };
    }

which, know how to store isNew property

and a working sample:

 var savedFeature = new SavedFeature();
 console.log(savedFeature.savedItem); //  true by default

 savedFeature.stateMachine.set(savedFeature.savedItem); // saving state.
 savedFeature.savedItem.isNew = false; // modifying state
 console.log(savedFeature.savedItem); // return false, because of statement above

 var restoredState = savedFeature.stateMachine.get(); // restoring state
 console.log(restoredState); // true

 savedFeature.savedItem.isNew = restoredState.isNew;
 console.log(savedFeature.savedItem); // true

you can adjust that code, and reach functionality whatever you need. hope that helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!