Send Instances - adammcarth/instance.js GitHub Wiki

Sending off the Instance to a URL on the server is the ultimate goal of an Instance Model. Remember that you can define some .send(); related settings when defining the Instance Model, including the URL and Method for the request.

.send(); will send all of the current parameters associated with the Instance to the specified URL via an AJAX request. Initiating this is not difficult...

.send( url, method, validation );

var Comment = new Instance({
   name: "comment",
   url: "/comments/1/update",
   method: "put"
});
// Send the instance off to the server using the default
// settings. If no default settings have been specified,
// the URL defaults to "./", and method to "post".
Comment.send();

Or we can send the comment with some custom arguments...

Comment.send("/comments/new", "post");

A callback function is executed if the AJAX request is successful or not. To learn more about these (and other settings), read up on the settings guide.

Skipping Validation

If you've defined some client side validation rules in the instance model, Instance won't send the model to the server if they fail. To skip validation, simply pass false to the validation argument of the send function:

Comment.send("/comments/new", "post", false); // skip validation

Additional Callbacks

A new feature introduced in v1.1.0 was some extra callbacks for the send function. Use them from inside the model like so...

var Comment = new Instance({
   before_send: function() {
      alert("Instance is about to send your comment to the server!");
   },
   after_send: function() {
      alert("Instance just sent the comment!");
   }
});

A brief note on the name setting

By default, parameters will send as a "flat" structure. That is,

{ name: "Adam", message: "Hello, world!" }

If you pass in a name to the Instance settings, it will effect the way your parameters are sent. They will be converted into a two dimensional structure. This follows conventions from many MVC frameworks, such as Rails. Since the name was set to comment in the Instance example above - the parameters will now look like this:

{comment: { name: "Adam", message: "Hello, world" }}

This is achieved by changing the parameter to the following pattern: comment[parameter]=value. Be aware that some web frameworks will not support this.