This chapter describes how to use backbone to perform crud on webapis. We will operate on a dataset (for example, a message list in the guestbook ). For data sets, backbone has a special type-backbone. collection. For collection management, backbone. Collection has the add and remove events after it is created. The update of child elements needs to monitor the "change" event on the model. According to the initialized backbone. collection. URL, the collection will automatically assign URL/: ID to the child element, so the ID attribute should be defined in the model. On the other hand, the webapi structure of the server must comply with the specifications.
Overall:
Here we split a comment view and commentlistview split the fetch data one by one to create a commentview. Commentlistview responds to the deletion and addition operations of the UI.
Commentview and comment model:
var CommentModel = Backbone.Model.extend({idAttribute: "ID",urlRoot: 'api/comments'});var CommentView = Backbone.View.extend({el: '',template: _.template($('#commentTemplate').html()),initialize: function () {this.model.on('change', this.render, this);this.model.on('destroy', this.remove, this);},render: function() {var data = this.model.toJSON();this.$el.html(this.template(data));return this;},remove: function() {this.$el.remove();}});
Note: When the delete button is pressed for processing, you need to know which model to process. Therefore, when the template is generated, save the ID attribute of commentmodel to HTML.
<script id="commentTemplate" type="text/html"><li class="comment">
For list control: commentlist inherits from backbone. Collection, and commentlistview processes Delete and submit button events:
Commentlist. model. models is the set of commentmodel.
var CommentList = Backbone.Collection.extend({url: 'api/comments', model: CommentModel});var CommentListView = Backbone.View.extend({el: 'body',initialize: function () {this.model.on('reset', this.render, this);},events : {'click .delete': 'delete','click .submit': 'create'},render: function () {var self = this;$('#comments').empty();_.each(this.model.models, function(mdl) {var commentView = new CommentView({model: mdl});$('#comments').append(commentView.render().$el);});},delete: function(obj) {alert('delete: ' + $(obj.currentTarget).attr('id'));var id = parseInt($(obj.currentTarget).attr('id'), 10);var deletedModel = _.find(this.model.models, function(item) {return item.get('ID') === id;});var self = this;deletedModel.destroy({ success: function() { self.model.remove(deletedModel); }, error: self.errorHandle});},create: function() {var metaData = { ID: null, Text: $('#text').val(), Author: $('#author').val(), Email: $('#email').val(), GravatarUrl: '' };var comment = new CommentModel(metaData);var self = this;comment.save(metaData, { success: function(res) {console.log(JSON.stringify(res));self.model.add(res); var view = new CommentView({model: res});$('#comments').append(view.render().$el); }, error: self.errorHandle });},errorHandle: function(model, xhr, options) {var err = $.parseJSON(xhr.responseText);alert(err.ExceptionMessage);}});
According to the definition of backbone, the model will "inherit" the URL from the collection. URL, and then add the ID attribute. However, if the newly created model (add operation) is used, the URL corresponding to the new model cannot be obtained. Therefore, we can see that the urlroot attribute is added to the Code of the above commentmodel to ensure that the newly created model can also be mapped to the correct URL. Here, compared with knockout, backbone needs to write more code, but is more flexible. Backbone. sync in backbone encapsulates the Ajax logic. Knockout needs to call Ajax on its own.