BindEvent Storage - single page system

Share your advanced knowledge/code with the community.
User avatar
eddy
Posts: 124
Joined: Thu Mar 27, 2014 8:34 am

BindEvent Storage - single page system

Post by eddy »

- LocalStorage handles events between tabs
- SessionStorage handles events between frames from same tab (I didn't test this case)

Open two tabs with the same page URL, then sees what happens:

Code: Select all

Procedure BindEvent_Storage(*StorageChanged)
  !window.addEventListener('storage', function (event) {
  !    p_StorageChanged(event.key, event.oldValue, event.newValue, event.storageArea == localStorage);
  !},false);        
EndProcedure

CompilerIf #PB_Compiler_IsMainFile
  ; *************************
  ; EXAMPLE 
  ; *************************
  
  Import ""
    SetLocalStorage(Key.s, Value.f) As "localStorage.setItem"
    GetLocalStorage.f(Key.s) As "localStorage.getItem"
    SetLocalStorageString(Key.s, Value.s) As "localStorage.setItem"
    RemoveLocalStorage(Key.s) As "localStorage.removeItem"
    ClearLocalStorage() As "localStorage.clear"
  EndImport
  
  #UNIQUE_PAGE="My SpiderBasic Page Is Unique!"
  
  
  Procedure GenerateId()
    NewValue=Date()
    SetLocalStorage(#UNIQUE_PAGE,NewValue)
    SetGadgetText(40,""+NewValue)
  EndProcedure
  
  Procedure CloseMe()
    Static isClosed
    If Not isClosed
      isClosed=1
      OpenWindow(1,0,0,400,400,"Test", #PB_Window_Background)        
      TextGadget(2,5,5,200,30,"I became a SECONDARY page")
      TextGadget(40,5,50,400,20,"")      
    EndIf 
    If isClosed
      SetGadgetText(40,"Now, the new PRIMARY page is: "+GetLocalStorage(#UNIQUE_PAGE)) 
    EndIf 
    ProcedureReturn isClosed
  EndProcedure
  
  Procedure StorageChanged(Key$,OldValue,NewValue, IsLocalStorage)
    Debug Key$+" : "+OldValue+" : "+NewValue+" : "+IsLocalStorage
    If IsLocalStorage
      If Key$=#UNIQUE_PAGE      
        CloseMe()          
      EndIf           
    EndIf     
  EndProcedure
  
  Procedure CloseOthers()    
    GenerateId()    
    OpenWindow(1,0,0,400,400,"Single page instance", #PB_Window_Background)        
    TextGadget(2,5,5,200,20,"I am the PRIMARY page!")
    ButtonGadget(30,5,30,100,20,"GENERATE ID: ")
    TextGadget(40,5,60,100,20,""+GetLocalStorage(#UNIQUE_PAGE),#PB_Text_Center)
    BindGadgetEvent(30,@GenerateId())    
  EndProcedure
  
  If GetLocalStorage(#UNIQUE_PAGE)
    OpenWindow(1,0,0,400,400,"Single page instance", #PB_Window_Background)        
    TextGadget(2,5,5,200,30,"Can I close other pages ?")
    ButtonGadget(3,5,45,70,20,"YES")
    ButtonGadget(4,90,45,70,20,"NO")
    BindGadgetEvent(3,@CloseOthers())
    BindGadgetEvent(4,@CloseMe())
  Else 
    CloseOthers()
  EndIf 
  BindEvent_Storage(@StorageChanged())  ;it will observe LocalStorage changes from other tabs  
CompilerEndIf