JavaScriptMVC

From JavaScriptMVC

Jump to: navigation, search

Models wrap an application's data layer. This is done in two ways:

  • Requesting data from and interacting with services
  • Wrap service data with a domain-specific representation

A strong model layer keeps your code organized and maintainable, but it typically is the least developed part of the MVC architecture. This guide introduces you to the basics of how a model should work.

Contents

Model Classes

There are different types of models for connecting to different services. Model is the most basic model class. Most models are based around a transport (a way of getting data). Examples of transport based models include: Model.Ajax, Model.JsonP, and Model.WindowName. Model.XmlRest and Model.JsonRest models wrap REST services of a given type. Finally, Model.Cookie provides a model for browser-based cookies.

Interacting with Services

Models should be the way your app communicates with the server. Instead of using Ajax/XHR requests directly, perform those requests in a model.

For example:

//instead of:
new Ajax('/tasks.json', {onComplete: find_tasks_next_week })
//do this:
Task.find('all', find_tasks_next_week)
 
//instead of
new Ajax('/tasks/'+id+'/complete.json',{onComplete: task_completed})
//do this:
task.complete(task_completed)

Typically there are two types of services any application connects to:

  • Group - operate on many instances. Ex: getting all tasks for a user.
  • Singular - operate on one instance. Ex: completing a task.

For these types of services, you will want to build them in slightly different ways.

Group Services

Group services that request data should look like the following:

Task = MVC.Model.extend('task',
{
  find : function(params, callback){
    new Ajax('/tasks.json', {onComplete: MVC.Function.bind(function(response){
        //get data into the right format for create_as_existing
        var data =  eval('('+json_string+')');     
        //call create_as_existing to create instances
        var instances = this.create_many_as_existing(data);
        //call back with data.
        callback(instances)
    }) })
  }
},
{})

Note this function uses create_many_as_existing to create new instances. By using create_many_as_existing, the model will also publish OpenAjax.hub messages that can be listed to by controllers.

Singular Service

Singular services that minipulate data might look like:

Task = MVC.Model.extend('task',
{},
{
  complete: function(callback){
    new Ajax('/tasks/'+this.id+'/complete.json', {onComplete: MVC.Function.bind(function(response){
        this.completed = true;
        callback(this)
        this.publish("completed")
    }) })
  }
})

Wrapping Data

Now that you have instances, you can wrap their data in useful ways. This is done by adding functions to the Model's prototype methods. For example:

Task = MVC.Model.extend('task',
{},
{
  status : function(){
    return this.complete ? "COMPLETE" : "INCOMPLETE"
  }
})