Connecting the form to a Javascript object (and other best practices)

I've been using javascript to make things easier on sites for years - DOM manipulation, etc, but I'm now starting to research it to do a lot more heavy lifting (combined with PHP). I just started working in OO JS and I am still trying to think about the best practices and design patterns that work well with it.

To be more specific - my question is, can anyone here suggest methods for connecting a form to a javascript object?

In my current implementation, I have a JS object that can be edited by a (rather large) form. When I instantiate an object, I attach an onchange observer to the form whose callback synchronizes the form fields with the object's parameters. I am processing a form submitted via AJAX - there is also a periodic request that saves a temporary version of the form information to the mySQL database. I wonder if the synchronization in the other direction can be easily handled - when replacing an object, update the form fields (e.g. in a reset form).

I am curious to see if this approach is correct / sane and overall I would be very interested to hear some advice regarding OOJS form handling.

Cheers in advance :)

(Im using Prototype btw)

0


source to share


3 answers


you can use $("form").serialize(true);

http://www.prototypejs.org/api/form/serialize



You don't need the onchange event, you can just call the serialize () method every time you need to get the form data.

+2


source


Why not create a method on the object that resynchronizes the object with the form? And call it every time the object changes? You can create a custom change function to ensure that it gets called on every change.



0


source


This is a perfectly reasonable approach. JS does not fully support such things due to its curious object system and, in particular, the methods that the associated methods are bound to are not first-class objects, but with a little suitable metaclass and backbranding, it is eminently possible.

You can also look at the widget library if you want to get more of this kind of low-level form processing for free. Have not tried the ones built on top of the prototype; other features include YUI.

Updating a model from the server can be pretty straightforward. Typically, you should poll the AJAX request and send either a diff if it knows them to the server, or just flag each object update, send the new object data to the client side on each update, and ask the client to decide how to combine this with any changes made by the user Meanwhile.

0


source







All Articles