public
Description: Provides REST functionality for javascript objects via ajax
Homepage:
Clone URL: git://github.com/ratnikov/ajax_resource.git
README.rdoc

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.