Is it possible to listen for changes to an object's attributes in JavaScript?

后端 未结 7 1678
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 23:37

I\'m working on a fiddly web interface which is mostly built with JavaScript. Its basically one (very) large form with many sections. Each section is built based on options

相关标签:
7条回答
  • 2020-12-03 00:18

    As far as I know, there are no events fired on Object attribute changes (edit: except, apparently, for Object.watch).

    Why not use event delegation wherever possible? That is, events on the form rather than on individual form elements, capturing events as they bubble up?

    For instance (my jQuery is rusty, forgive me for using Prototype instead, but I'm sure you'll be able to adapt it easily):

    $(form).observe('change', function(e) {
        // To identify changed field, in Proto use e.element()
        // but I think in jQuery it's e.target (as it should be)
    });
    

    You can also capture input and keyup and paste events if you want it to fire on text fields before they lose focus. My solution for this is usually:

    1. Gecko/Webkit-based browsers: observe input on the form.
    2. Also in Webkit-based browsers: observe keyup and paste events on textareas (they do not fire input on textareas for some reason).
    3. IE: observe keyup and paste on the form
    4. Observe change on the form (this fires on selects).
    5. For keyup and paste events, compare a field's current value against its default (what its value was when the page was loaded) by comparing a text field's value to its defaultValue

    Edit: Here's example code I developed for preventing unmodified form submission and the like:

    What is the best way to track changes in a form via javascript?

    0 讨论(0)
提交回复
热议问题