0

I have 2 buttons which are change status of variable, If status is 1 it shows div, if not it hides dive. I need to catch this variables changes and add condition inside different script, which will work without page refresh and will add or hide script depends on variable. Here is example code:

var point_access = 0;

document.getElementById('button 1').onclick = function() {
  if (point_access == 0) {
    point_access = 1;
    //do smth else
  }
}

document.getElementById('button 2').onclick = function() {
  if (point_access == 1) {
    point_access = 0;
    //do smth else
  }
}

Here is the code that I want to show or hide script, which is depends on variable point_access

map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      //smth here
    }),
    new ol.layer.Tile({
      //smth here
    }),
    vectorLayer //this is the variable inside script which i want to show or hide
    //if(point_access == 1){
    //  vectorLayer
    //}
  ],
  //smth else
});

So, how can I do it work live? It all time get point_access value as 0 and do not listen to my value change on click.

Orik00
  • 73
  • 1
  • 9
  • [javascript-event-listener-for-changes-in-an-object-variable](https://stackoverflow.com/questions/5860218/javascript-event-listener-for-changes-in-an-object-variable) – absin Jan 18 '19 at 13:10

1 Answers1

1

The problem is that the code you want to react to the variable change has already run by the time the variable changes. You need to get it to run again to re-check for the variable. Without the rest of your code I can't see exactly how that would happen, but you'll need to either redeclare the map or update it.

For example:

document.getElementById('button 1').onclick = function() {
  if (point_access == 0) {
    point_access = 1;
    updateTheMap();
    //do smth else
  }
}

Alternatively, you could turn your variable into an object:

point_access = {
   value: 0,
   updateValue: function(value) {
     this.value = value;
     updateTheMap();
   }
}

Then you can get the value of point_access with point_access.value and set it with point_access.updateValue(1), and the map will update:

document.getElementById('button 1').onclick = function() {
  if (point_access == 0) {
    point_access.updateValue(1);
    //do smth else
  }
}

You'll still need to come up with an updateTheMap function of course.

Ian
  • 5,704
  • 6
  • 40
  • 72
  • @Orik00 I'm not sure if you're asking for that function or not, but if you are, it would be something like `map.layers[3] = vectorLayer` but it depends on the library you're using. – Ian Jan 22 '19 at 13:05