On Sep 22, 8:17 pm, Alex Wibowo <alexwib...@gmail.com> wrote:
> Hi...
>
> I'm trying to write object-oriented style javascript as follows:
>
> -----------------------------
> function HtmlFormUtil(formId){
>     this.formId=formId;
>     this.dirtyInputs=new Array();}
>
> HtmlFormUtil.prototype.trackForChanges=function(){

     var dirtyInputs = this.dirtyInputs;


>    $(":input","#"+this.formId).change(function(){
>           this.dirtyInputs[this.dirtyInputs.length]=$(this);

           dirtyInputs[dirtyInputs.length] = $(this);

and so on. Why you need to use $(this) is beyond me, just store a
reference to the element. Get its value by direct access to the DOM
property.

>    });}
>
> HtmlFormUtil.prototype.isDirty=function(){
>    return this.dirtyInputs.length > 0;}

Seems you are using this array as nothing more than a glorified
counter. Why not just increment a global counter, rather than creating
a global object with circular references to every input element in the
page?

e.g. something like

 function addOne() {
    numChanged++;
 }
 var numChanged = 0;
 var inputs = document.getElementsByTagName('input');
 var i = inputs.length;
 while (i--) {
  inputs[i].onchange = numChanged;
 }
 inputs = null;

>
> -------------------------------
>
> The intention is to use it to track any changes to the form fields... and
> warn user on window unload, if there's any dirty inputs (i.e
> form value has changed)

It will be problematic. If the user re-sets the form, do you reset the
dirtyInputs array? If the user changes the value back to the original,
do you remove the input from the array? If they paste data into the
input, will the change event fire before it navigates away?

If there is only going to be one instance of this object in the page,
why use a constructor? Just use a plain object and give it the methods
you are putting on the prototype. Not as hip, funky or cool, but
cleaner and less problematic.

>
> Unfortunately, the code above doesnt work... because  in
> "this.dirtyInputs[....]",   the "this" keyword refers to the element that
> has the value
> changed (i.e. jquery object)

No, the DOM element.

>,   and not     'this instance of HtmlFormUtil'.

You'll find it's not particularly useful anyway. Just compare each
input's value to its defaultValue. If they're different, the user
changed it. You don't even care *how* they changed it.

Note however that an onunload listener will break fast history
navigation in some browsers.


> Has anyone ever done this before?

A thousand times.

> What is the best way to solve my problem
> above?

Use something like:

  if (input.defaultValue != input.value) {
    // value has changed.
  }



--
Rob

Reply via email to