Preliminary backbone.js (rpm)

BackBone is JavaScript frameworks for creating MVC-like web applications, recently popular tool used to create single-page web application, following and using a Restful JSON framework.

Backbone by providing a model Models, collections Collection, View gives view Web application hierarchy. Tiered structure in the following ways:

  • Model Model binding key data and custom events, represented in all application data, data models can be created, check, destruction and save to the server , when the models in value is changed automatically trigger a "change" event, All models are representative of the views of data will be listening to this event, and then re-rendered
  • Colection model is a collection of ordered or unordered collection, with abundant enumerate the API; the JAVA class set and we usually contact with similar elements having increased, remove elements, acquiring length, sorting, comparing tools series method, it means a saving models of collections.
  • View View declare event listener function; View can bind dom el and client events. Html page is rendered by the render method views, and when you want to create a new view through the pass into a model as data, for example:
    var view = new EmployeeView({model:employee});  

    That model is carried out in this way and view associated

Model, set, RESTful JSON interface with the server's view.
Backbone must rely on Underscore.js, DOM AJAX request operation and rely on Zepto / one third party jQuery / ender, may also be provided by other third-party libraries Backbone.setDomLibrary (lib).

Feature

  • Creating models or views of grammar: extends, the equivalent of class inheritance
  • models of creation, destruction, verification and a series of changes will trigger a corresponding event

Examples

Requirements: to achieve an editable form with backbone.js employee information and jquery.

Features: 1, enter employee information. 2, delete employee information. 3. Double-click the table can be modified employee information. 4, to check the effectiveness of employee information. 5, can be persistent information to employees.

design:

With the Employee class (inherited from Backbone .Model ) indicating that employee information, including ID, name, gender, age and job fields.

    = window.Employee Backbone.Model.extend ({
         // model values of the check 
        the validate: function (attrs) {
             for ( var Key in attrs) {
                 IF (attrs [Key] == '' ) {
                     return Key + "is not empty " ; 
                } 
                IF (Key == 'Age' && isNaN (attrs.age)) {
                     return " Age must be a number " ; 
                } 
            } 
        } 
    });

 After declaring the Employee class can be a new example of the object of the Employee:

var employee = new Employee();

Employee class does not have to declare ID, name and other business fields. When you need to set this information to the employee, you can just call

employee.set({'id':1,'name':'Jason'}); 

Of course, if the employee is required to verify the information required to configure a validate method Employee class, this method attrs parameter is set into the json data. Thus, when the employee changes the data inside each of the first call will validate this method.

After a good start Model class definition can define a set of classes, you can add, delete, and a series of operations for each Model class inside the collection inside, you can also call the fetch method to obtain an initial set of values ​​from the server side.

    = window.EmployeeList Backbone.Collection.extend ({ 
        Model: the Employee, 
        // persisted to local database 
        localStorage: new new Store ( "the Employees" ), 
        
    }); 
    window.Employees = new new the EmployeeList ();

 After setting localStorage property Employees inside the data is automatically synchronized to the local database stored inside, whenever the call Employees.fetch () and then will recover data from localStorage inside.

 View class is responsible for all the work and interface-related, such as html template binding, the binding interface elements of the event, the initial rendering, re-rendering the model values change and the destruction of interface elements such as:

= window.EmployeeView Backbone.View.extend ({ 
        tagName: 'TR' , 
        Template: _.template ($ ( '#-Template Item' ) .html ()), 
        Events: {
             "DblClick TD": "Edit" ,
             "Blur INPUT, SELECT": "Close" ,
             "the Click .del": "Clear" , 
        }, 
        the initialize: function () {
             // each time updating the model to re-render 
            the this .model.bind ( 'Change', the this . the render, the this );
             // automatically removed after each model delete the UI 
            the this .model.bind ( 'destroy', this.remove, this);
        },
        setText : function(){
            var model = this.model;
            this.input = $(this.el).find('input,select'); 
            this.input.each(function(){
                var input = $(this);
                input.val(model.get(input.attr("name")));
            });
        },
        close: function(e) {
            var input = $(e.currentTarget);
            var obj = {};
            obj[input.attr('name')] = input.val();
            this.model.save(obj);
            $(e.currentTarget).parent().parent().removeClass("editing");
        },
        edit : function(e){
            // 给td加上editing样式
            $(e.currentTarget).addClass('editing').find('input,select').focus();
        },
        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
            //The value of each cell is given a hidden input field 
            the this .setText ();
             return  the this ; 
        }, 
        Remove: function () { 
            $ ( the this .el) .remove (); 
        }, 
        Clear: function () {
           the this . model.destroy (); 
        } 
});

 This class code inside more, but the main interface and rendering related. EmployeeView object corresponds to a table inside a tr element. Each time a new object when EmployeeView will first call the initialize method, this method is an event which is bound to ensure the tr element corresponding to the value of each model is deleted or changed will be synchronized to the interface. That is when the data each time the user interface modifications are saved first change to the current model object view bound inside, and then model the inside of the event mechanism automatically triggers a "change" Event of the interface to be modified.

template method _.template ($ ( '# item- template '). html ()) is used in the aforementioned underscore.js tool provides a method to generate dynamic HTML through the HTML template interface and a JSON , it means the value which is filled into JSON HTML template corresponding placeholder inside, cattle X is an HTML template which support some common logical expression, such as if, else, foreach like:

        <script type="text/template" id="item-template">
            <td><%= eid %></td>
            <td class="username">
                <div class="display"><%= username %></div>
                <div class="edit"><input class="username" name="username"></input></div>
            </td>
            <td class="sex">
                <div class="display"><%= sex=="1" ? "":"" %></div>
                <div class="edit">
                <select name="sex" class="sex" style="width:45px">
                    <option value="0"></option><option value="1">女</option>
                </select>
                </div>
            </td>
            <td class="age">
                <div class="display"><%= age %></div>
                <div class="edit">
                    <input class="age" name="age"></input>
                </div>
            </td>
            <td class="position">
                <div class="display"><%= position %></div>
                <div class="edit">
                    <input class="position" name="position"></input>
                </div>
            </td>
            <td>
                <a href="#" class="del">删除</a>
            </td>
        </script>

 setText method is mainly responsible for the model is provided to each of the data inside a hidden input field inside tr inside.

close method is bound to blur event input and select elements. When the user of the cell data would be modified to interface to a mouse click input box and the rest are hidden automatically and modify the data displayed in the table above. First, the implementation of validate method model after close method first to get the latest value from the currently edited element, then packaged as an object, call the save method of the model, if the check is passed then saved to a local store and triggers a "change" event.

 Finally, you need a master interface View , The View is mainly bound to "add" button event entry form interface, Employees of related events and page restore data from a local store initialization:

window.AppView = Backbone.View.extend({
        el : $("#app"),
        events : {
            "click .#add-btn" : "createOnEnter"
        },
        // 绑定collection的相关事件
        initialize: function() {
            Employees.bind('add', this.addOne, this);
            // 调用fetch的时候触发reset
            Employees.bind('reset', this.addAll, this);
            Employees.fetch();
        },
        createOnEnter : function(e) {
            var= Employee new new the Employee ();
             var attr = {}; 
            $ ( '# EMP-form INPUT, SELECT # EMP-form') each (. function () {
                 var INPUT = $ ( the this ); 
                attr [input.attr ( 'name')] = input.val (); 
            }); 
            employee.bind ( 'error', function (model, error) { 
                Alert (error); 
            }); 
            // SET process model will automatically call the validate method verify, if not through it returns false 
            IF (employee.set (attr)) { 
                Employees.create (Employee);  
            }
        },
        addOne : function(employee){
            employee.set({"eid":employee.get("eid")||Employees.length});
            employee.bind('error',function(model,error){
                alert(error);
            });
            var view = new EmployeeView({model:employee});
            $(".emp-table tbody").append(view.render().el);
        },
        addAll : function(){
            Employees.each(this.addOne);
        }
});

 initialize method bound Employees of add and reset events, which means that every time a model is added to the Employees of the time will call addOne AppView method, this method is mainly bound to the error event model and the generated html insert EmployeeView interface to the appropriate location.

OK, everything is ready, only a strong start, initialization method is applied throughout the initialize method AppView , so only you need to create a AppView on it:

window.App = new AppView(); 

JS code entire sample is small, since the example uses local storage, so do not run with exemplary IE

 Reprinted from: http: //weakfi.iteye.com/blog/1391990

Reproduced in: https: //www.cnblogs.com/JoannaQ/p/3251251.html

Guess you like

Origin blog.csdn.net/weixin_34297300/article/details/93056614
rpm