0

Is there a way of adding a listener or binding an event to a value instead of a html element?

So an event is triggered when a value changes instead of when you click a button, etc...

Hypothetical code:

var changingValue = 1;

$('button').on('click',function(){
    changingValue = changingValue + 1;
});

$(changingValue).on('change',function(){
    alert("event triggered, the new value is:" + this)
});
qwertynl
  • 3,912
  • 1
  • 21
  • 43
Sam Jones
  • 4,443
  • 2
  • 40
  • 45
  • I don't understand, if you click on the button, the value is incremented. There is your change event. – Sterling Archer Jan 13 '14 at 17:00
  • `changingValue` should be a valid selector. – Alvaro Jan 13 '14 at 17:00
  • For example, i have an integer which is modified by several methods. Adding an event to the value being changed would be simpler and less code than adding the same event to several other methods. The duplicate questions don't have proven answers within the past 4 years which is why i asked again. Thanks for the comments. – Sam Jones Jan 13 '14 at 17:13

1 Answers1

1

You can if you use an object like so:

function Changing(initialValue, valueListener) {
    this._value = initialValue;
    this._listener = valueListener;
}
Object.defineProperties(Changing.prototype, {
    value: {
        get: function() {
            return this._value;
        },
        set: function(value) {
            this._value = value;
            this._listener(this._value);
        }
    }
});

Then you can do:

var changingValue = new Changing(1, function(value) {
    alert("event triggered, the new value is: " + value);
});

$('button').on('click',function(){
    changingValue.value += 1; // will alert "event triggered, the new value is: ..."
});
qwertynl
  • 3,912
  • 1
  • 21
  • 43
  • thanks, seems to do the trick. Any idea on browser compatibility? – Sam Jones Jan 13 '14 at 17:30
  • 1
    It should work in all modern browsers, but there is a polyfill [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties#Polyfill) if you need it @SamJones – qwertynl Jan 13 '14 at 17:32