views:

48

answers:

3

In my Javascript drag and drop build app, a variety of buildings can be built. The specific characteristics of these are all saved in one object, like

var buildings = {
house: ['#07DA21',12,12,0,20],
bank: ['#E7DFF2',16,16,0,3],
stadium: ['#000000',12,12,0,1],
townhall: ['#2082A8',20,8,0,1],
etcetera
}

So every building has a number of characteristics, like color, size, look which can be called as buildings[townhall][0] (referring to the color). The object changes as the user changes things. When clicking 'reset' however, the whole object should be reset to its initial settings again to start over, but I have no idea how to do that. For normal objects it is something like.

function building() {}
var building = new building();
delete building;
var building2 = new building();

You can easily delete and remake it, so the properties are reset. But my object is automatically initialized. Is there a way to turn my object into something that can be deleted and newly created, without making it very complicating, or a better way to store this information?

+1  A: 

You can keep initial state as a prototype on an object.

var Base = function(){};
    Base.prototype={a:1,b:2};
var c = new Base();

Now, you can change value of a or b to whatever you want. To restore, just use

delete c.a or delete c.b

You will get your initial value back. Hope this help.

Fopfong
A: 

Just use a copy/clone method to restore the original state

var defaults = {
    foo: "bar"
};
var building;

function reset(){
    building = {};
    for (var key in defaults) {
        if (defaults.hasOwnProperty(key){
            building[key] = defaults[key];
        }
    }
}

Now you can just call reset() whenever you need to have building reset.

Sean Kinsey
A: 

Thanks for your answers. I had hoped for some sort of feature I had missed to do this very easily. With your help though, I have come up with a solution, that at least achieves what I want. So thanks for the help; don't know if I should or should not set a green arrow on a specific solution then?

Pino
Yes, so everyone on SO can see that your question got answered properly and doesn't need attention anymore. Just mark the most helpful answer.
Marcel Korpel