1

Is there a way to add an event listener/handler to a JavaScript object? Preferably using JQuery.

Such as:

var foo;
$(foo).bind('change', function() {
   alert("Foo has changed!");
 });

I have tried this, but nothing seems to happen. Does this only work with DOM elements?

EDIT: I need an event fired every time that the audio or video tags throw an error. Originally, I was using an interval to check whether or not the error, media.error, object was null, but this uses excess processing power and I would like to avoid it.

EDIT 2: Apparently I was going about it wrong, easiest way I found was to add the onerror property to the video/audio tag.

4 Answers 4

1

I agree with Cheeso that it's more important for you to state what you actually want to do, however one workaround for your specific question could be to store your variable within an object and only provide access through getter / setter, then you can do what you want in the setter. e.g.

function data() {
    var foo = 0;

    this.setFoo = function(newVal) {
        foo = newVal;
        alert(foo);
    };
}

var theData = new data();

theData.setFoo(5);
Sign up to request clarification or add additional context in comments.

Comments

0

Yes, that's correct. You cannot make a "variable watcher". There is no event fired for variables when they are changed.

What are you really trying to do?

Comments

0

You could try: http://higginsforpresident.net/js/static/jq.pubsub.js

See http://weblog.bocoup.com/publishsubscribe-with-jquery-custom-events

Or use a framework like backbone/underscore or knockout.js.

Comments

0

HTML/Elements/audio

    var foo;
    $(foo).bind('error', function() {     
       //your code here
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.