From my littleexperience in Flex, I learned about Bindable variables, so that the content of a text element changed with th value of a variable, for example.
I’m wondering if it’s possible to do such a thing in JavaScript. For instance, suppose I have an <h1 id="big_title"> that I want to contain the document’s title. That can easily be done with document.getElementById('big_title').innerHTML = document.title;, but what if document.title changes? I’d have to manually update big_title as well.
Another way of putting it, is there a way to create a custom onchange-like event handler on a variable rather than a DOM element? This handler could update the title as needed.
EDIT: I know I could use a setInterval to check for variable “bindings” (defined in an array) and update as needed, but this would be somewhat hack-ish and would require a compromise between responsiveness and impact on performance.
You can “watch” objects in most major browsers. Here is a shim. The idea essentially is to have a setter (in that example it’s the function called
handler) that will be executed when the value changes. I’m not sure what the extent of browser support is.Although to be honest it sounds like a much easier solution to have your own setter method. Either make it into an object (you can easily extend this example to use a generic
handlerinsetad of always changing the title):Or if it isn’t something you need to instantiate multiple times, a simple function + convention will do: