My favorites | Sign in
Project Logo
                
Search
for
Updated Sep 05, 2008 by adambones
Labels: Featured, Phase-Implementation
Requests  
Send asynchronous requests and handle the responses

Send Ajax requests with request(method, url, parameters).

When you do so, the calling component is responsible for handling the server response. When the response arrives, an appropriate callback is looked for:

  • add(element) An OK response with HTML
  • update(object) An OK with JSON
  • remove An OK response for a DELETE request
  • error(content) An error response
  • handle(code, content) Any response (called if no other callback is found)

For example:

bind('page', {

  run: function() {

    // Returns an OK with JSON - calls update()
    this.request('PUT', this.path, { value: 'Ya' });
    
    // Returns an error with HTML - calls error()
    this.request('DELETE', this.path);
  },

  update: function(object) {
    alert('That was a good update: ' + object.value);
  },

  error: function() {
    this.notices.append('<span class="notice">Error!</span>');
  }
});

Note that the update and remove are already implemented as described, but you could override them (like above).

The default implementation of add delegates to a method of the form addX, where x is a component yielded by the element, allowing you to respond to different components arriving from the server application:

bind('note');
bind('photo');

bind('scrapBook', {

  onClickSave: function() {
    this.request('GET', '/photos/3.html');
    return false;
  },

  addNote: function(note) {
    this.append(node).appear();
  },
  
  addPhoto: function(photos) {
    this.gallery.append(photo);
  }
});

For compatibility with frameworks like Rails and Merb, PUTs and DELETEs are simulated using a _method parameter with POST.


Sign in to add a comment
Hosted by Google Code