Javascript MVC framework backbone. js details

  • 2020-03-30 03:57:46
  • OfStack

As JavaScript programs become more complex and often require a team to work together, modularity and organization of the code becomes extremely important. The MVC pattern is a classic pattern of code organization.

(...... Introduction to MVC.)

(1) Model

The Model represents the data layer, which is the data source required by the program, typically in JSON format.

(2) the View

View represents the presentation layer, the user interface, and in the case of a web page, the HTML code that the user sees on the web page.

(3) the Controller

The Controller represents the control layer, which is used to process the raw data (Model) and pass it to the View.

Because web programming is different from client-side programming, on the basis of MVC, the JavaScript community produced various variations of the framework MVP (model-view-presenter), MVVM (model-view-viewmodel), and so on, some people call all the various patterns of this kind of framework collectively called MV*.

The advantage of the framework is that it is well organized, easy to work with and maintain in the future. The disadvantage is that it has a certain learning cost and limits you to the way it is written.

Backbone of the load


<script src="/javascripts/lib/jquery.js"></script>
<script src="/javascripts/lib/underscore.js"></script>
<script src="/javascripts/lib/backbone.js"></script>
<script src="/javascripts/jst.js"></script>
<script src="/javascripts/router.js"></script>
<script src="/javascripts/init.js"></script>

Backbone. View

Basic usage

The backbone. View method is used to define the View class.


var AppView = Backbone.View.extend({
  render: function(){
    $('main').append('<h1> Primary title </h1>');
  }
});

The above code defines a View class AppView through the extend method of backbone. View. Inside the class is a render method that places the view on the web page.

When used, you need to create a new instance of the view class, and then through the instance, call the render method, so that the view is displayed on the page.


var appView = new AppView();
appView.render();

The code above creates a new instance of the view class AppView, AppView, and then calls appview.render, and the specified content is displayed on the page.

When you create a new view instance, you usually need to specify the Model.


var document = new Document({
  model: doc
});

The initialize method

The view can also define the initialize method, which is automatically called when an instance is generated to initialize the instance.


var AppView = Backbone.View.extend({
  initialize: function(){
    this.render();
  },
  render: function(){
    $('main').append('<h1> Primary title </h1>');
  }
});
var appView = new AppView();

After the initialize method is defined in the above code, the step of manually calling appview.render () after the instance is generated is omitted.

El attribute, $el attribute

In addition to specifying the page element that the view is bound to directly in the render method, you can also specify the page element with the view's el attribute.


var AppView = Backbone.View.extend({
  el: $('main'),
  render: function(){
    this.$el.append('<h1> Primary title </h1>');
  }
});

The above code and the render method directly bind the page elements, the effect is exactly the same. In the above code, there is also the $el attribute, which represents the specified DOM element, and the $el attribute, which represents the jQuery object corresponding to that DOM element.

TagName property, className property

If you do not specify the el attribute, you can also specify it through the tagName attribute and the className attribute.


var Document = Backbone.View.extend({
  tagName: "li",
  className: "document",
  render: function() {
   // ...
  }
});

The template method

The view's template property is used to specify the page template.


var AppView = Backbone.View.extend({
      template: _.template("<h3>Hello <%= who %><h3>"),
});

In the above code, the template function of the underscore function library takes a template string as an argument and returns the corresponding template function. With this template function, you can generate web code by providing specific values.

var AppView = Backbone.View.extend({
      el: $('#container'),
      template: _.template("<h3>Hello <%= who %><h3>"),
      initialize: function(){
        this.render();
      },
      render: function(){
        this.$el.html(this.template({who: 'world!'}));
      }
});

The render in the above code calls the template method to generate the concrete page code.

In practice, templates are usually placed in script tags. In order to prevent browsers from parsing by JavaScript code, the type attribute is set to text/template.


<script type="text/template" data-name="templateName">
    <!-- template contents goes here -->
</script>

You can compile the template using the following code.

window.templates = {};
var $sources = $('script[type="text/template"]');
$sources.each(function(index, el) {
    var $el = $(el);
    templates[$el.data('name')] = _.template($el.html());
});

The events property

The events property is used to specify the view's events and their corresponding handlers.


var Document = Backbone.View.extend({
  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  }
});

A click event in the above code that specifies three CSS selectors and its corresponding three handlers.

Listento method

The listento method is used to specify a callback function for a specific event.


var Document = Backbone.View.extend({
  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  }
});

The above code is the change event of the model, specifying the callback function as render.

The remove method

The remove method is used to remove a view.


updateView: function() {
  view.remove();
  view.render();
};

subview

Child views can be called from the parent view. Here's one way to write it.


render : function (){
    this.$el.html(this.template());
    this.child = new Child();
    this.child.appendTo($.('.container-placeholder').render();
}

Backbone. The Router

Router is a routing object provided by Backbone to map the url requested by a user to a back-end handler.

First, define a new Router class.


Router = Backbone.Router.extend({
    routes: {
    }
});

Routes properties

The most important of the Backbone.Router objects is the routes property. It is used to set the processing method of the path.

The routes property is an object, each member of which represents a path handling rule, the key name is the path rule, and the key value is the handling method.

If the key is called an empty string, it represents the root path.


routes: {
        '': 'phonesIndex',
},
phonesIndex: function () {
        new PhonesIndexView({ el: 'section#main' });
}

The asterisk represents any path, and you can set path parameters to capture specific path values.

var AppRouter = Backbone.Router.extend({
    routes: {
        "*actions": "defaultRoute"
    }
});
var app_router = new AppRouter;
app_router.on('route:defaultRoute', function(actions) {
    console.log(actions);
})

In the above code, the parameters after the root path are captured and passed in the callback function.

Path rules.


var myrouter = Backbone.Router.extend({
  routes: {
    "help":                 "help",   
    "search/:query":        "search"
  },
  help: function() {
    ...
  },
  search: function(query) {
    ...
  }
});
routes: {
  "help/:page":         "help",
  "download/*path":     "download",
  "folder/:name":       "openFolder",
  "folder/:name-:mode": "openFolder"
}
router.on("route:help", function(page) {
  ...
});

Backbone. History

Once the router is set up, you can start the application. The backbone. history object is used to monitor url changes.


App = new Router();
$(document).ready(function () {
    Backbone.history.start({ pushState: true });
});

Turn on the pushState method. If the application is not in the root directory, you need to specify the root directory.

Backbone.history.start({pushState: true, root: "/public/search/"})
Backbone.Model

The Model represents a single object entity.

var User = Backbone.Model.extend({
        defaults: {
            name: '',
            email: ''
        }
});
var user = new User();

The code above USES the extend method to generate a User class that represents the model's template. Then, using the new command, generate an instance of the Model. The defaults property is used to set the default property. The code above says that the user object has two default properties, name and email, whose values are equal to an empty string.

When an instance is generated, you can provide specific values for individual attributes.


var user = new User ({
    id: 1,
    name: 'name',
    email: 'name@email.com'
});

The above code provides the specific values for each property when it generates the instance.

IdAttribute properties

An instance of the Model must have a property that ACTS as a primary key to distinguish between other instances. The name of this attribute, set by the idAttribute attribute, is usually set to id.


var Music = Backbone.Model.extend({
    idAttribute: 'id'
});

The get method

The get method is used to return the value of a property of the Model instance.


var user = new User({ name: "name", age: 24});
var age = user.get("age"); // 24
var name = user.get("name"); // "name"

Set method

The set method is used to set the value of a property of the Model instance.


var User = Backbone.Model.extend({
    buy: function(newCarsName){
        this.set({car: newCarsName });
    }
});
var user = new User({name: 'BMW',model:'i8',type:'car'});
user.buy('Porsche');
var car = user.get("car"); // ' Porsche'

On methods

The on method is used to listen for changes to the object.


var user = new User({name: 'BMW',model:'i8'});
user.on("change:name", function(model){
    var name = model.get("name"); // "Porsche"
    console.log("Changed my car's name to " + name);
});
user.set({name: 'Porsche'});
// Changed my car's name to Porsche

The on method in the above code is used to listen for events, and "change:name" indicates that the name attribute has changed.

Urlroot properties

This property is used to specify the path for the server-side operation on the model.


var User = Backbone.Model.extend({
    urlRoot: '/user'
});

The above code specifies that the path of the server pair to the Model should be /user.

The fetch event

The fetch event is used to fetch the Model from the server.


var user = new User ({id: 1});
user.fetch({
    success: function (user){
        console.log(user.toJSON());
    }
})

In the above code, the user instance contains an id attribute (value 1), and the fetch method USES the HTTP verb GET to make a request to the url "/user/1" to fetch the instance from the server.

Save method

The save method is used to tell the server to create or update the Model.

If a Model instance does not have an id attribute, the save method creates the instance using the POST method.


var User = Backbone.Model.extend({
    urlRoot: '/user'
});
var user = new User ();
var userDetails = {
    name: 'name',
    email: 'name@email.com'
};
user.save(userDetails, {
    success: function (user) {
        console.log(user.toJSON());
    }
})

The above code first specifies in the class that the url corresponding to the Model is /user, then creates a new instance, and finally calls the save method. It takes two arguments, the first is a concrete property of the instance object, and the second is a callback function object that sets the callback function of the success event (save successfully). Specifically, the save method sends a POST request to /user and provides {name: 'name', email:' name@email.com'} as data.

If a Model instance contains an id attribute, the save method updates the instance with the PUT method.


var user = new User ({
    id: 1,
    name: ' Zhang SAN ',
    email: 'name@email.com'
});
user.save({name: ' Li si '}, {
    success: function (model) {
        console.log(user.toJSON());
    }
});

In the above code, the object instance has an id attribute (value 1), and save will use the PUT method to request the url "/user/1" to update the instance.

Destroy methods

The destroy method is used to delete the instance on the server.


var user = new User ({
    id: 1,
    name: 'name',
    email: 'name@email.com'
});
user.destroy({
    success: function () {
       console.log('Destroyed');
    }
});

The destroy method in the above code, which USES the HTTP verb DELETE, makes a request to the url "/user/1" to DELETE the corresponding Model instance.

Backbone. The Collection

A Collection is a Collection of the same class of models. For example, a Model is an animal while a Collection is a zoo. A Model is a single person, and a Collection is a company.


var Song = Backbone.Model.extend({});
var Album = Backbone.Collection.extend({
    model: Song
});

In the code above, Song is Model and Album is Collection, and an Album has a Model attribute equal to Song, so it indicates that an Album is a Collection of songs.

Add method, remove method

An instance of the Model can be placed directly into an instance of the Collection, or it can be added with the add method.


var song1 = new Song({ id: 1 ,name: " Da da da 1", artist: " Zhang SAN " });
var song2 = new Music ({id: 2,name: " Da da da 2", artist: " Li si " });
var myAlbum = new Album([song1, song2]);
var song3 = new Music({ id: 3, name: " Da da da 3",artist:" Zhao Wu " });
myAlbum.add(song3);

The remove method is used to remove a Model instance from a Collection instance.

myAlbum.remove(1);

The above code indicates that the argument to the remove method is the id attribute of the model instance.

Get method, set method

The get method is used to get an instance of the Model with the specified id from the Collection.


myAlbum.get(2))

The fetch method

The fetch method is used to fetch the Collection data from the server.


var songs = new Backbone.Collection;
songs.url = '/songs';
songs.fetch();

Backbone. Events

var obj = {};
_.extend(obj, Backbone.Events);
obj.on("show-message", function(msg) {
    $('#display').text(msg);
});
obj.trigger("show-message", "Hello World");


Related articles: