Every repository with this icon (
Every repository with this icon (
| name | age | message | |
|---|---|---|---|
| |
.gitignore | Mon Feb 23 16:05:24 -0800 2009 | |
| |
README.rdoc | Fri Feb 27 14:44:26 -0800 2009 | |
| |
Rakefile | Mon Feb 23 15:52:35 -0800 2009 | |
| |
ajax_resource.gemspec | Wed Mar 04 15:22:40 -0800 2009 | |
| |
jake.yml | Fri Feb 27 14:34:13 -0800 2009 | |
| |
lib/ | Tue Feb 24 20:40:14 -0800 2009 | |
| |
spec/ | Tue Feb 24 12:43:32 -0800 2009 | |
| |
src/ | Wed Mar 04 15:12:39 -0800 2009 | |
| |
tasks/ | Mon Feb 23 19:22:31 -0800 2009 | |
| |
test/ | Wed Mar 04 15:12:39 -0800 2009 |
Ajax Resource - Javascript implementation of REST resource
Installation
Update Rakefile
To include the ajax_resource installation tasks, add following to Rakefile:
require 'task/ajax_resource'
Run installer task
To install, run the ajax_resource:rails:install task:
rake ajax_resource:rails:install
This will install ajax_resource-src.js and ajax_resource-min.js to Rails.root/public/javascripts directory.
AjaxResource.Form
AjaxResource.Form allows to make a form handle submission and error handling of an AjaxResource.
Example
Suppose you have a form to create a new Story resource, such as:
<div class="new-story-form { 'author_id' : 5 }">
<div class="error" style="display: none"><p>Please review following errors:</p><ul></ul></div>
<label for="body"><p>Your story:</p></label>
<textarea name="story[body]"></textarea></p>
<input type="submit" value="Publish" /></p>
</div>
<ul class="story-list">
</ul>
In your story.js file you would need to specify the Story resource with something like:
var Story = function(spec) {
this._author_id = spec.author_id;
// initialize the AjaxResource.Base functionality
AjaxResource.Base.apply(this, [ { resource : 'story', controller : 'stories' } ]);
};
// include the AjaxResource.Base functionality
jQuery.extend(Story.prototype, AjaxResource.Base.prototype);
// override the prefix to be 'user/authors/:author_id'
Story.prototype.prefix = function() {
return '/user/authors/' + this._author_id;
};
Finally, hook form functionality into the created form using the Story model:
jQuery(document).ready(function() {
jQuery("div.new-story-form").each(function() {
var form = this;
var story_form = new AjaxResource.Form(this, {
on_create: function(model) {
alert("Successfully created a story!");
// add the story html to the story list
jQuery('ul.story-list').prepend("<li>"+story.html()+"</li>");
},
model: function() {
// build a new story using the author_id specified in metadata of this form
// (using jQuery metadata plugin)
return new Story(form.metadata().author_id);
}
});
});
});
And that’s it! If the returned request contains errors (e.g. { "story" : { "errors" : [ [ "Body", "is blank" ] ] } }) it will automatically update the ul in the errors div. If the story was successfully created, it will invoke the on_create callback with the update story passed as parameter.







