Model.Ajax makes it easy to write models that handle the request / reponse cycle of most
Ajax driven applications. It helps you escape transporting callbacks.
It uses convention to tie function names to resouces/ urls. This is best shown with an example:
First, lets say we wanted an FTP model to be able to requests data from /ftp/dir. We could create that
model like this:
Ftp = MVC.Model.Ajax.extend('ftp',
{
dir_get_success: function(transport){
return transport.responseText;
}
},{})
You could make a request to /ftp/dir like this:
callback = function(data){alert(data)};
Ftp.dir({path: "/"}, callback)
There are a few things to notice here.
- Ftp.dir function expects params as its first argument. These will post path="/" to /ftp/dir
- There are no callbacks in the Ftp model. You return the data you want passed to the callback in dir_get_success
- dir_get_success is called with the result of the transport.
- The get makes the request use the HTTP verb get. You can use put/post/get/delete. If no verb is present, it defaults
to post.
Model.Ajax allows you to expand on this pattern in several ways:
Changing the request path
If /ftp/dir was actually ftp_directory, you can change the directory name by adding the following:
Ftp = MVC.Model.Ajax.extend('ftp',
{
dir_get_url: '/ftp_directory'
dir_get_success: function(transport){
return transport.responseText;
}
},{})
dir_get_url could also be a function that dynamically returns the url. For example,
...
dir_get_url: function(params){
return "/ftp/dir/"+encodeURIComponent(params.path)
}
...
would return "/ftp/dir/%2F" for Ftp.dir({path: "/"}, callback)
Customizing and validating the request
You can completely customize the request by making a function like X_request. Where X matches one of your success functions.
The following example validates that params must include a path.
...
dir_get_request: function(params){
if(!params.path) throw "Path does not exist!"
}
...
In a request function, you can also completely customize the request with the temporary this.request function.
Example:
...
dir_get_request: function(params){
if(!params.path) throw "Path does not exist!"
this.request("/ftp/dir/"+encodeURIComponent(params.path)+".json")
}
...
Respond to errors
Finally, you can respond to Transport errors in the same way you respond to success:
Ftp = MVC.Model.Ajax.extend('ftp',
{
dir_get_success: function(transport){
return transport.responseText;
},
dir_get_failure: function(transport){
return "error data"
}
},{})