JSON Circular Object Type Reviver

I am creating a game in a web application that uses custom circular objects that the user can manipulate and save. All objects are connected to a circular player object, which is stored using Circular-JSON .

An application requires storing object types, but JSON does not. I can’t declare a type for each individual object, because a player can have a couple of hundred objects of different types. I saw some regenerators that are of a type, but not a generic one, or one that will work with circular objects.

For instance:

function Room(name, description){
            this.type = "room";
    this.name = name;
    this.description = description;
    this.roomItems = [/*array of items randomly set*/];
    this.exits = [/*array of rooms set */];
}

function Item(name, description, weight){
            this.type = "item";
    this.name = name;
    this.description = description;
    this.weight = weight;
    this.components = [/*array of items*/];
    this.contents = [];
    this.setContents = function(item){
        this.contents.push(item);
        this.weight += item.weight;
    }
}

function Player(startroom){
            this.type = "player"
    this.weightLimit = 20;
    this.totalWeight = 0;
    this.currentRoom = startroom; //this is a room
    this.playerItems = [/* An array of Items */]; 
    this.moveCount = 0;
}

The application saves and downloads through:

function saveGame(){    
    var d = new Date()
    player.lastsave = d.toISOString();
    localStorage.setItem('player', CircularJSON.stringify(player));
}

function loadGame(){
    declareStart(); //loads the same as a start
    player =  CircularJSON.parse(localStorage.getItem('player', reviver)); 
}

The examiner I tried looks like this:

function reviver(k, v){
        switch (v.type) {
            case "room":
                $.extend(v, Room.prototype);
                break;
            case "item":
                $.extend(v, Item.prototype);
                break;
            case "player":
                $.extend(v, Player.prototype);
                break;
        }
        return v;
    }

, , .

reviver, ? ?

, , ?

+4
1

@kahjav. , Object.create, , . . : https://gist.github.com/jameswomack/6e6462f9c6ae5d9b9072

- , CircularJSON, , , CircularJSON.

, ,

function get(key, Proto) {
  var result = JSON.parse(this.store[key]);
  return key === Proto.name.toLowerCase() ? reviveFromJSONResult(result, Proto) : result;
}

function reviveFromJSONResult(result, Proto) {
  var value = Object.create(Proto);
  for (var key in result) {
    value[key] = result[key];
  }
  value[Proto.name.toLowerCase()] && (value[Proto.name.toLowerCase()] = value);
  return value;
}

var person = get('person', Person);

( , ), . . "~".

+1

Source: https://habr.com/ru/post/1544047/


All Articles