Skip to content

Instantly share code, notes, and snippets.

@michael
Created September 2, 2008 16:08
Show Gist options
  • Select an option

  • Save michael/8424 to your computer and use it in GitHub Desktop.

Select an option

Save michael/8424 to your computer and use it in GitHub Desktop.
/* AutoSaveResourceProxy */
/*
forms must look like that:
<form id="quote_option_2_form" action="/quotes/1/quote_options/2" method="post">
<input type="hidden" name="_method" value="put"/>
</form>
it even works with a normal div element - conventions are like so:
<div id="quote_option_2">
<input type="hidden" name="_action" value="/quotes/1/quote_options/2"/>
<input type="hidden" name="_method" value="put"/>
</div>
*/
var AutoSaveResourceProxy = new Class({
Implements: [Options, Events],
options: {
className: 'autosave',
contentType: 'json',
onStart: $empty,
onRequestComplete: $empty,
onRequestFailure: $empty
},
initialize: function(element, options) {
// merge options
this.setOptions(options);
this.element = $(element);
// grab the action if element is a form
this.action = this.element.get('action');
this.method = this.element.get('method');
// if element is just a normal element grab the info from
actionInput = this.element.getElement("input[name=_action]");
methodInput = this.element.getElement("input[name=_method]");
if (actionInput)
this.action = actionInput.get('value');
if (methodInput)
this.method = methodInput.get('value');
this.browserMethod = (this.method=="get") ? "get" : "post";
// register events for the autosave fields
this.registerEvents();
},
registerEvents: function() {
$$("#"+this.element.get('id')+" ."+this.options.className).each(function(item, index) {
item.addEvent('change', this.dispatch.bind(this)); // bit crazy?
}.bind(this));
},
dispatch: function() {
// Ajax Request for quoteoption, method-dependent
var jsonRequest = new Request.JSON({url: this.action+"."+this.options.contentType,
onComplete: function(resource) {
// expects an html property as well as a errors array
// delegate to onRequestComplete
this.fireEvent('requestComplete', resource); // user may manipulate the dom here!!
// what about reassigning events after dom manipulations now?
}.bind(this),
onFailure: function() {
// delegate to onRequestFailure
this.fireEvent('requestFailure');
// reassigning events after dom manipulations goes here!
}.bind(this),
})[this.browserMethod](this.element); // element will be serialized and therefore parameters added to the request
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment