[V2] Global Context


#1

How can i define a global context Variable. Forexample i would like to access current user date from any template without always having to request it or redefine it in everypage.

So I just store it once in a Javascript Variable but I cant access this in template


#2

When you init the app you can set global data:

var app = new Framework7({
  data: function () {
    return {
      userName: 'johndoe',
    }
  }
});

And later you can access like app.data.username or in templates as a $root.username


#3

is there a way to redefine that data?


Sending data to other page onclick event list view F7 [V.2]
#4

app.data.userName = ‘anotherusername’


#5

but i cant redefine the whole object or?

what i have noticed, ( i must say i am still a amateur developer) that once i defined

data: function () { 
 return window.user.info
 }

The app.data always updates automaticly with the change of window.user.info


#6

did you try

app.data = newDataObj;

#7

yup that deosn’t work,


#8

Hi @Momo,

You can set value on global context using below js script

app.data.name=‘rajkaruna’

Then you can retrieve this value in template like below

{{$app.data.name}}

Check component context topic below url for more details


#9

hmm for some reason it deosnt work for me

is it maybe because i Init the app after redefining the app.data variable?


#10

@Momo,

You should set values to the global context once app is initialized.


#11

I have tired with {{ $root.userName }} in the index page, but it is not working…


#12

Sorry, I have tired in the index page, it is not working, but it is working in the other pages, is it mean I need replace all centent from index page, then try to use templete rending in the index page to access the root data? I really have no idea what i should do with it… Please help…


#13

JS variables don’t work like that. Define method instead like:

methods: {
  userData() {
    return window.user.info;
  },
},