Created
November 28, 2025 12:21
-
-
Save nicodevs/5e79980ad6802f0424bed32377592141 to your computer and use it in GitHub Desktop.
Backbone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Backbone To-Do App with $.getJSON</title> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.1/backbone-min.js"></script> | |
| </head> | |
| <body> | |
| <div id="app"></div> | |
| <script type="text/template" id="app-template"> | |
| <h2>To-Do List (<%= count %>)</h2> | |
| <ul> | |
| <% todos.forEach(function(todo) { %> | |
| <li><%= todo.title %></li> | |
| <% }) %> | |
| </ul> | |
| </script> | |
| <script> | |
| // Model | |
| var Todo = Backbone.Model.extend({ | |
| defaults: { | |
| title: '' | |
| } | |
| }); | |
| // Collection | |
| var TodoList = Backbone.Collection.extend({ | |
| model: Todo | |
| }); | |
| // Main App View | |
| var AppView = Backbone.View.extend({ | |
| el: $('#app'), | |
| template: _.template($('#app-template').html()), | |
| initialize: function() { | |
| var self = this; | |
| $.getJSON('/api/todos', function(data) { | |
| self.collection.reset(data); | |
| self.render(); | |
| }); | |
| // this.listenTo(this.collection, 'add remove reset', this.render); | |
| }, | |
| render: function() { | |
| var html = this.template({ | |
| todos: this.collection.toJSON(), | |
| count: this.collection.length | |
| }); | |
| this.$el.html(html); | |
| return this; | |
| } | |
| }); | |
| // Empty collection at start | |
| var todos = new TodoList(); | |
| // Initialize app | |
| var appView = new AppView({ collection: todos }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment