简体   繁体   中英

how to implement javascript localStorage

I want to implement localStorage for one of my values in my Achievements class. So basically what this class does is take player data from backend database and if a player clears certain tasks an achievement gets unlocked. For now I have just 1 achievement defined as follows

Achievements:{ 1:{name:'First_Achievement',status:1} },

The status field acts like a flag for my achievements. If status is 1 then achievement is still locked and if it goes 0 the achievement gets unlocked.

This is a skeleton code for when my achievement gets unlocked. This block of code is checked in my game every 10 seconds to see if a certain task is cleared to unlock an achievement

      checkAchievements:function(){ 
      this.probsSolved = this.getTeamProbSolved(); 
      if( this.Achievements[1].status == 1 && this.probsSolved.length >=3)  
          this.triggerAchievement(1); // spawns achievement 1 on screen                   
          this.Achievements[1].status = 0; 
      },

So this works fine when I run the game. The "this.Achievements[1].status" is set to 0 until I start my game again the next time. It sets the "this.Achievements[1].status" back to 1 and the if loop runs again as status is set back to 1 which I don't want because its obvious I want my achievement to be spawned or displayed just once and not every time I run the game.

So how do go about an implement localStorage here? I suppose I need to store my "Achievements.status" field in the localStorage so that the if loop runs just once and not everytime. Or is there any other way I can implement this?

I tried the following

localStorage.setItem(this.Achievements[1].status,0);

but it does not work

any help would be appreciated! Thanks!

First, I'd recommend reading the documentation on localStorage at MDN - https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage . Next, let's look at your call:

localStorage.setItem(this.Achievements[1].status,0);

This says: I want you to store a value, 0, and retrieve it by the key that is the value of this.achievements[1].status.

That seems to be booleans for you. So you basically did:

localStorage.setItem(true, 0)

The localStorage API expects a string for the keyname, so it will get the string value of true which is, true. So it probably did work for you, but you used a key that probably isn't what you want. You need to think of a key name scheme that makes sense for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM