Javascriptmvc tutorial-2. Quick Start (on)

Source: Internet
Author: User
Tags findone

We will introduce the basic functions of javascriptmvc by creating an application named todo.

  

  Obtain javascriptmvc

You can get javascriptmvc by downloading or using git, https://github.com/downloads/jupiterjs/javascriptmvc/javascriptmvc-3.2.4.zip. It consists of four sub-projects. Once you get javascriptmvc, you will get the following directory structure. The current directory is the root directory:

Documentjs-document engine funcunit-test the application of jquery-jquery and the jquerymx plugin steal-dependency management tool js-Linux/mac js command line tool JS. Bat-Windows JS command line tool

 

  Run javascriptmvc

Jmvc uses steal/steal. js as the dependency management tool and can use it to load JS files. For example, if you want to use steal to load $. Controller and $. view, you can use the following method:

Steal ('jquery/controller', 'jquery/View/ejs', function () {// Where controller and view are used })

To use steal, you need to add the steal tag to the page. Under the root directory, upload the todosdirectory, empty todos.html and todos. JS, as shown in the following figure:

ROOT\    documentjs\    jquery\    funcunit\    steal\    todos\      todos.js      todos.html

The content of todos.html is as follows:

<!DOCTYPE html>

You can use the Firefox browser to open the page and use firebug to view loading of steal. js and todos. js.

 

  StealSteal ([paths])

Steal is used to load JS, CSS, coffeescript, less, and template files to your application. The steal path is related to the root path. No matter what directory the page file that references the following code is under, jquery/class. js will be loaded under the root directory.

steal('jquery/class/class.js');

This method is equivalent to the following:

steal('//jquery/class/class.js');

The reference file can be prefixed with the current path file ./:

steal('./helpers.js')

Steal also supports loading CSS files,

steal('./todos.css')

The previous course also mentioned that loadingJquery/class. js can use the following method:

steal('jquery/class')

Because steal is an asynchronous record, do not use the following method:

Steal ('jquery/class') $. Class // things that can only be done after loading jquery/call

Instead, use the following method:

Steal ('jquery/class', function () {$. Class // What is done after jquery/class is loaded })

In our todos application, we need to load the plug-in files related to jquerymx to the todos. js file:

steal('jquery/class',      'jquery/model',      'jquery/dom/fixture',      'jquery/view/ejs',      'jquery/controller',      'jquery/controller/route',      function($){})

Next we will look at the jquerymx plug-ins to be used.

 

  $. Class$. Class ([name,] [classprops,] [prototypeprops])

Using the $. Class constructor to create a class instance will contain shared attributes. $. Controller, $. model is created through it. To use $. Class to create your own class, you need to provide the following parameters:

  • Name: Class Name, which can be used for class self-description;
  • Classproperties: Static attribute, which can be used by the constructor object;
  • Prototypeproperties: Prototype attribute, used by the class instance.

$. Class uses the prototype chain, so you can extend the required subclass as needed:

steal('jquery/class', function(){  $.Class("Todo",{    init : function(){},    author : function(){ ... },    coordinates : function(){ ... },    allowedToEdit: function(account) {      return true;    }  });  Todo('PrivateTodo',{    allowedToEdit: function(account) {      return account.owns(this);    }  })});

$. Class provides the _ super method, which allows you to access a function with the same name on the prototype chain. It can be understood as accessing a parent function:

var SecureNote = Todo({  allowedToEdit: function(account) {    return this._super(account) &&        this.isSecure();  }})

 

  Constructor/initNew Class (arg1, arg2)

When the constructor of the class is called, $. Class creates an instance object and passes the parameter to $. Class. Prototype. init to execute the init method. Before the init method is implemented, the setup method will be executed, which can be used to affect the parameters passed to the init method.

$.Class('Todo',{  init : function(text) {    this.text = text  },  read : function(){    console.log(this.text);  }})var todo = new Todo("Hello World");todo.read()

 

  Model$. Model (name, classproperties, prototypeproperties)

Model is the center of any application. It contains data and business logic. You can extend $. Model to implement your own methods. At the same time, it provides a series of methods for managing instance changes. To create a model instance, you must pass the following parameters:

  • Name: Class Name;
  • Classproperties: Static attributes, including findall, findone, create, update, and destroy attributes;
  • Prototypeproperties: Prototype attribute, used by the class instance.

In the following method, create a todo model in Todos. JS:

steal('jquery/class',      'jquery/controller',      'jquery/model',      'jquery/view/ejs',      'jquery/dom/fixture',      function($){  $.Model('Todo',{    findAll : "GET /todos",    findOne : "GET /todos/{id}",    create  : "POST /todos",    update  : "PUT /todos/{id}",    destroy : "DELETE /todos/{id}"  },  {})});

Note: You can use the following command in the browser command box.

  New $. Model (attributes)

Create a todo instance:

var todo = new Todo({name: "do the dishes"});

  ATTR Model. ATTR (name, [value])

  $. Model. Prototype. ATTR read or set the attributes of the model instance.

todo.attr('name') //-> "do the dishes"todo.attr('name', "wash the dishes" );todo.attr('name') //-> "wash the dishes"

The execution result in the browser. Chrome browser:

  Interaction with servers

The model uses static findall, findone, create, update, and destroy methods to go to instances on the CREATE, read, update, and delete servers. Now you can use the static method on todo to modify the data on the server. Enter the following statement in the command line:

Todo.findAll({});

He will request get/todos from the server and run the result:

  

You can use $. fixture to simulate the request.

 

  $. Fixture $. fixture (URL, fixture (original, settings, headers ))

$. Fixture simulates a request for a specific URL and uses the following parameters:

  • Original: Original settings passed to $. Ajax;
  • Settings: $. Ajax Standard settings;
  • Header: Request header.

The returned result is in the following array format:

return [ status, statusText, responses, responseHeaders ];

The actual result may be as follows:

return [ 200, "success", {json: []}, {} ];

If the returned array has only one value, it is assumed that it is JSON-type data. Load the following code into the steal callback function to simulate the todo Server:

// todos listsvar TODOS = [    {id: 1, name: "wake up"},    {id: 2, name: "take out trash"},    {id: 3, name: "do dishes"}];// findAll$.fixture("GET /todos", function(){  return [TODOS]});// findOne$.fixture("GET /todos/{id}", function(orig){  return TODOS[(+orig.data.id)-1];})// createvar id= 4;$.fixture("POST /todos", function(){  return {id: (id++)}})// update$.fixture("PUT /todos/{id}", function(){  return {};})// destroy$.fixture("DELETE /todos/{id}", function(){  return {};})

Now you can use the Ajax method of model to perform the CRUD operation on todos.

  Findall (Params, success (Todos), error ())

Findall gets multiple todo instances:

Todo.findAll({}, function( todos ) {  console.log( todos );})

Running result:

  

  Findone (Params, success (Todos), error ())

Findone gets a todo instance:

Todo.findOne({}, function( todo ) {  console.log( todo );})

Running result:

 

 

  Save todo. Save (success (Todo), error ())

Save checks whether the instance is created on the server. If the instance is not created, run the create method. If the instance is created, run the update method. The following example creates a todo instance and runs the Save method:

var todo = new Todo({name: "mow lawn"})todo.save(function(todo){  console.log( todo );})

Running result:

The following example creates a todo instance and modifies its attributes to execute the Save method:

var todo = new Todo({name: "mow lawn"});todo.save( function(todo){  console.log("created", todo );  todo.attr("name", "mow my lawn")  todo.save( function( todo ) {    console.log("updated", todo );  })})

Running result:

The above shows the effect of code execution. We can see that he sent two requests to the server. However, it is interesting that the returned class results are the same, as if {name: "Mow lawn"} does not play a role. Is the first request failed? In fact, because the last execution result is displayed twice, the first request still runs normally.

  

  Destroy todo. Destroy (success (Todo), error ())

The destroy method deletes an instance from the server.

var todo = new Todo({name: "mow lawn"});todo.save( function(todo){  console.log("created", todo );  todo.destroy( function( todo ) {    console.log("destroyed", todo );  })})

Running result:

 

 

  Bind todo. BIND (event, handler (EV, Todo ))

You can use bind to listen for changes to a single or all todo instances. For example, the following example monitors todo created:

var todo = new Todo({name: "mow lawn"});todo.bind('created', function(ev, todo){  console.log("created", todo );})todo.save()

Running result:

The following method is used to monitor the created of all todo instances:

Todo.bind('created', function(ev, todo){  console.log("created", todo );})

The model provides the following listening events for classes and instances:

  • Created-Create an instance on the server
  • Updated-The instance is updated on the server.
  • Destroyed-The instance is destroyed on the server.

 

  $. FN. Model $ (EL). Model ([modelinstance])

Marking an HTML element with a model instance may be quite useful and can be retrieved. Jquery. FN. model is used to set or obtain a model instance on an HTML element, as shown in the following example:

var li = $('<li>').model( new Todo({id: 5}) )                  .appendTo("#todos");

It will add 'todo todo_5 'to the classname of 'lil'. The running result is as follows:

We can use the following method to obtain the model instance:

li.model().id //-> 5

Running result:

  Elements todo. Elements ([Context])

You can use elements to obtain HTML elements that contain model instances. You can use jquery context to limit the query range. For example, the following example:

todo.elements('#todos');

 

 

Javascriptmvc tutorial directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.