Backbone is a set of classes, less than 4Kb in size, that form the structure of your code and help you create high-quality MVC web applications.Backbone forms the structure of heavy JavaScript applications, adding models with key-value storage and similar events, collections with rich API, views (orig. Views) with declarative event handling and combines all of this into one application that supports the RESTful JSON interface.
Backbone gives us the opportunity to separate the data from the presentation. A model that works with data and synchronizes with the server, then when the view listens to changes in the model and changes its state (renders the data in HTML)Immediately list the answers to questions that may arise now:
Backbone is extremely light, less than 4kb.In fact, about 4kb is not true: Backbone 4kb + Underscore.js 3kb + jQuery 31kb = 38kb
Models are the heart of all JavaScript applications that contain interactive data as well as most of the logic that surrounds them: transformations, validation, computed properties, and access rights.A model is a way to read and write properties or attributes in a data set. Here is an example of a model:
var Game = Backbone.Model.extend({});
var Game = Backbone.Model.extend({ initialize: function(){ alert("Oh hey! "); }, defaults: { name: 'Default title', releaseDate: 2011, } });
// var portal = new Game({ name: "Portal 2", releaseDate: 2011}); // releaseDate var release = portal.get('releaseDate'); // 2011 // portal.set({ name: "Portal 2 by Valve"});
portal.save();
var GamesCollection = Backbone.Collection.extend({ model : Game });
var GamesCollection = Backbone.Collection.extend({ model : Game, old : function() { return this.filter(function(game) { return game.get('releaseDate') < 2009; }); } });
var games = new GamesCollection games.get(0);
games.at(0);
var GamesCollection = Backbone.Collection.extend({ model : Game, url: '/games' }); var games = new GamesCollection games.fetch();
fetch
method, which leads to an asynchronous request for data from the server and fills the collection. var GameView = Backbone.View.extend({ tagName: "div", className: "game", render: function() { // } });
render : function() { this.el.innerHTML = this.model.get('name'); // jQuery: $(this.el).html(this.model.get('name')); }
events: { 'click .name': 'handleClick' }, handleClick: function(){ alert('In the name of science... you monster'); // Other actions as necessary }
var GameView = Backbone.View.extend({ initialize: function (args) { _.bindAll(this, 'changeName'); this.model.bind('change:name', this.changeName); } });
bindAll
is an Underscore method that binds this context to a function. This is especially useful in events.changeName
. You can use other prefixes instead of change:
to poll the state of the model. var Hashbangs = Backbone.Controller.extend({ routes: { "!/": "root", "!/games": "games", }, root: function() { // }, games: function() { // } });
!/games
will be associated with the function while the URL in the browser will be domain/#!/games
. // var ApplicationController = new Controller; Backbone.history.start();
#hash
change and alerts controllers.content
, order
and done
. window.Todo = Backbone.Model.extend({ // , // , default EMPTY: "empty todo...", // `content`, initialize: function() { if (!this.get("content")) { this.set({"content": this.EMPTY}); } }, // `done` toggle: function() { this.save({done: !this.get("done")}); }, // localStorage clear: function() { this.destroy(); this.view.remove(); } });
window.TodoList = Backbone.Collection.extend({ // Todo model: Todo, // "todos" localStorage localStorage: new Store("todos"), // , done: function() { return this.filter(function(todo){ return todo.get('done'); }); }, // , remaining: function() { return this.without.apply(this, this.done()); }, // , . // GUID . . nextOrder: function() { if (!this.length) return 1; return this.last().get('order') + 1; }, // comparator: function(todo) { return todo.get('order'); } }); // window.Todos = new TodoList;
// DOM window.TodoView = Backbone.View.extend({ // tagName: "li", // // template: _.template($('#item-template').html()), // DOM, events: { "click .check" : "toggleDone", "dblclick div.todo-content" : "edit", "click span.todo-destroy" : "clear", "keypress .todo-input" : "updateOnEnter" }, // TodoView . // ---, // . initialize: function() { _.bindAll(this, 'render', 'close'); this.model.bind('change', this.render); this.model.view = this; }, // render: function() { $(this.el).html(this.template(this.model.toJSON())); this.setContent(); return this; }, // XSS `jQuery.text` setContent: function() { var content = this.model.get('content'); this.$('.todo-content').text(content); this.input = this.$('.todo-input'); this.input.bind('blur', this.close); this.input.val(content); }, // "done" toggleDone: function() { this.model.toggle(); }, // edit: function() { $(this.el).addClass("editing"); this.input.focus(); }, // , close: function() { this.model.save({content: this.input.val()}); $(this.el).removeClass("editing"); }, // `enter`, updateOnEnter: function(e) { if (e.keyCode == 13) this.close(); }, // DOM remove: function() { $(this.el).remove(); }, // clear: function() { this.model.clear(); } });
window.AppView = Backbone.View.extend({ // , HTML el: $("#todoapp"), // // statsTemplate: _.template($('#stats-template').html()), // , events: { "keypress #new-todo": "createOnEnter", "keyup #new-todo": "showTooltip", "click .todo-clear a": "clearCompleted" }, // : // , , . , // localStorage initialize: function() { _.bindAll(this, 'addOne', 'addAll', 'render'); this.input = this.$("#new-todo"); Todos.bind('add', this.addOne); Todos.bind('refresh', this.addAll); Todos.bind('all', this.render); Todos.fetch(); }, // - . . render: function() { var done = Todos.done().length; this.$('#todo-stats').html(this.statsTemplate({ total: Todos.length, done: Todos.done().length, remaining: Todos.remaining().length })); }, // . `<ul>` addOne: function(todo) { var view = new TodoView({model: todo}); this.$("#todo-list").append(view.render().el); }, // addAll: function() { Todos.each(this.addOne); }, // newAttributes: function() { return { content: this.input.val(), order: Todos.nextOrder(), done: false }; }, // return - . // createOnEnter: function(e) { if (e.keyCode != 13) return; Todos.create(this.newAttributes()); this.input.val(''); }, // , . clearCompleted: function() { _.each(Todos.done(), function(todo){ todo.clear(); }); return false; }, // . showTooltip: function(e) { var tooltip = this.$(".ui-tooltip-top"); var val = this.input.val(); tooltip.fadeOut(); if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout); if (val == '' || val == this.input.attr('placeholder')) return; var show = function(){ tooltip.show().fadeIn(); }; this.tooltipTimeout = _.delay(show, 1000); } }); // - window.App = new AppView;
<!-- --> <div id="todoapp"> <div class="title"> <h1>Todos</h1> </div> <div class="content"> <div id="create-todo"> <input id="new-todo" placeholder="What needs to be done?" type="text" /> <span class="ui-tooltip-top" style="display:none;">Press Enter to save this task</span> </div> <div id="todos"> <ul id="todo-list"></ul> </div> <div id="todo-stats"></div> </div> </div> <!-- --> <script type="text/template" id="item-template"> <div class="todo <%= done ? 'done' : '' %>"> <div class="display"> <input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> /> <div class="todo-content"></div> <span class="todo-destroy"></span> </div> <div class="edit"> <input class="todo-input" type="text" value="" /> </div> </div> </script> <!-- --> <script type="text/template" id="stats-template"> <% if (total) { %> <span class="todo-count"> <span class="number"><%= remaining %></span> <span class="word"><%= remaining == 1 ? 'item' : 'items' %></span> left. </span> <% } %> <% if (done) { %> <span class="todo-clear"> <a href="#"> Clear <span class="number-done"><%= done %></span> completed <span class="word-done"><%= done == 1 ? 'item' : 'items' %></span> </a> </span> <% } %> </script>
Source: https://habr.com/ru/post/118782/
All Articles