Home > Enterprise >  How to create a custom event that triggers when a variable changes
How to create a custom event that triggers when a variable changes

Time:05-23

I am creating a custom widget with JavaScript and I need to create an event that triggers when a user changes a checkbox, for now I have a click event, but that doesn't work for what we want.

So I thought that creating a Custom Event is the way to go, and my idea is, I already have a variable that gets the value of the item that is selected, so I wanted to create a custom event that listen to this value and when it changes it will trigger the event. Don't know if this is the best way to do this, but this is my idea.

  this.addEventListener("selectedItem", event => {
    var eventSelectedItem = new CustomEvent("SelectedItem");
    console.log(selecteditem);
  })
    
function selecteditem(selectItem) {
  const selectedItem = _SelectItem // this is the variable that gets the value of the selected Item
    
    // now I don't know what to do here, I am reading a few things but this is the first time I am creating a custom event; 

    // I tried setters and getters but that I didn't understood how to make that work; 

    // Basically I need to save the last value and get the new value and then dispatch the event;
  
  selectItem.dispatchEvent(selecteditem);

}

Any help would be appreciated, either a new idea, or how to create this.

CodePudding user response:

You can use the pattern Observer https://en.wikipedia.org/wiki/Observer_pattern

here an excerpt from Wikipedia of the Javascript code

 let Subject = {
    _state: 0,
    _observers: [],
    add: function(observer) {
        this._observers.push(observer);
    },
    getState: function() {
        return this._state;
    },
    setState: function(value) {
        this._state = value;
        for (let i = 0; i < this._observers.length; i  )
        {
            this._observers[i].signal(this);
        }
    }
};

let Observer = {
    signal: function(subject) {
        let currentValue = subject.getState();
        console.log(currentValue);
    }
}

Subject.add(Observer);
Subject.setState(10);
//Output in console.log - 10

CodePudding user response:

If I understand what you mean, this is simpler than creating an event. You just need to add the code in the function

document.querySelectorAll("input").forEach(item => {
  item.addEventListener("change", event => {
      // Add your code here
  })
})
<input type="checkbox" id="Hello">
<label for="Hello">Hello</label>
<br>
<input type="checkbox" id="World">
<label for="World"`enter code here`>World</label>

CodePudding user response:

Well, with proxies you can track properties:

let obj = {
  myValue: 1
}

let proxy = new Proxy(obj, {
   get(obj, prop) {
      return obj[prop]
   },
   set(obj, prop, val){
      console.log("value changed")
      obj[prop] = val
   }
})


setInterval(() => {
   proxy.myValue  
},1000)

The set function is your trigger event, whenever you change your value proxy.myValue

Whenever the property value gets changed, the set function fires

  • Related