Backbone. js learning example
Start learning
What is backbone. js?
Meigong's understanding is a js mvc framework, which can be divided into Model, View, and Collection. If you have experience in mvc hierarchical development, it is easy to understand.
Why learning this?
It can be used to complete multiple application modules on a single page, giving users the feeling that they do not need to refresh the page and are suitable for webapp development.
$ (Function (){
Var testModel = Backbone. Model. extend ({
Defaults :{
Id: "1 ",
Name: 'meigong ',
Age: '22'
}
});
Var Collection = Backbone. Collection. extend ({
Model: testModel
});
Var ItemView = Backbone. View. extend ({
TagName: 'tr ',
Template: _.template(('{tpl-item'{.html ()),
Initialize: function (){
This. model. bind ('delete', this. unrender, this );
This. model. bind ('change', this. render, this );
},
Events :{
'Click a. edit': 'edititem ',
'Click a. del ': 'delitem ',
"Blur input, select": "saveItem"
},
EditItem: function (){
// Obtain all input
Var input = $ (this. el). find ('input ');
Input. each (function (k, v ){
$ (V). removeAttr ('Disabled ');
});
},
DelItem: function (){
// Delete from the collection
App. collection. remove (this. model );
},
SaveItem: function (){
Alert (2 );
},
Unrender: function (){
$ (This. el). remove ();
},
Render: function (){
Attributes (this.el).html (this. template (this. model. toJSON ()));
Return this;
}
});
Var View = Backbone. View. extend ({
El: $ ('# test '),
Template: _.template(('{tpl-student'{.html ()),
Initialize: function (){
// This. model. bind ("change", this. render, this );
This. render ();
This. collection = new Collection ();
This. collection. bind ('add', this. appendItem, this );
This. id = 0;
},
Events :{
'Click # btn ': 'additem'
},
AddItem: function (){
This. id ++;
This. testmodel = new testModel ();
This. testmodel. set ({
Id: this. id
});
// Add to collection
This. collection. add (this. testmodel );
},
AppendItem: function (){
Var itemView = new ItemView ({model: this. testmodel });
$ (This. el). append (itemView. render (). el );
},
Render: function (eventName ){
Optional (this.el).html (this. template ());
}
});
Var app = new View ();
});
Start Description: This example is a draft of the US public note. It is normal to run locally. If you copy the code, the file will be missing.
Modified location
1. Change the section in the backone-min.js to create: "POST", update: "POST", "delete": "DELETE", read: "GET"
2. The server accepts the post json data $ data = json_decode $ GLOBALS ['HTTP _ RAW_POST_DATA ']);
Template used
Main File Code
$ (Function (){
// Instantiate the index list
// Model of the index list
Var index_Model = Backbone. Model. extend ({
Url: "./get. php", // request address
});
// Set of models
Var index_Collection = Backbone. Collection. extend ({
Model: index_Model, // model layer contained in the Set
Url: './get. php' // request address
});
// View of each element
Var index_list_View = Backbone. View. extend ({
Template: _.template(('{tpl-item'{.html ()),
Initialize: function (){
This. model. bind ("change", this. render, this); // triggered when the set, add, and destroy parameters of the model are executed.
},
Events: {// bind event
'Click. bannerImg ': 'addnum ',
'Click. bannerinfo': 'comment'
},
AddNum: function (){
// The name displayed when you click the image changes
This. model. set ({// will trigger the change event
'Name': 'Hello Chao Jie ',
});
This. model. save (null, {// initiate a post request
Url: 'http: // www.biuman.com/test/before/update2'
})
},
Comment: function (){
Var id = this. model. get ('id ');
App. navigate ("comment/" + id, true); // hash navigation url
},
Render: function (){
Attributes (this.el).html (this. template (this. model. toJSON ()));
Return this;
}
});
// List View is a collection of index_list_View
Var index_item_View = Backbone. View. extend ({
Initialize: function (){
This. model. bind ('reset', this. render, this); // The model here is a set that is passed into index_Collection.
Var self = this;
This. model. bind ("add", function (item) {// executing the add operation in index_Collection will trigger the add operation or trigger the create request.
$ (Self. el). append (new index_list_View ({model: item}). render (). el );
});
},
Render: function (eventName) {// Rendering
// The model here is a set
_. Each (this. model. models, function (item ){
$ (This. el). append (new index_list_View ({model: item}). render (). el );
},
This );
Return this;
}
});
// Comment
Var comment_add_View = Backbone. View. extend ({
Template: _.template(('{tpl-comment'{.html ()),
Initialize: function (){
This. render ();
},
Events :{
'Click. btn ': 'addcom ',
},
AddCom: function (){
Var title = $ ("input [name = 'title']"). val ();
Var data = {
Title: title
}
// The app must be written here.
App. comment_collection.create (data ,{
Url: 'http: // localhost/ci/before/insert2 ',
Success: function (){
}
});
},
Render: function (){
Optional (this.el).html (this. template (); // directly write this. template () If no model exists (). This. model. toJSON () is used to parse a model into a string ()
Return this;
}
});
/*** Display Comments List Function Code explanation is the same as above **/
Var comment_Model = Backbone. Model. extend ({
Url: "./get. php ",
Defaults :{
Title :'',
}
});
Var comment_Collection = Backbone. Collection. extend ({
Model: comment_Model,
Url: 'http: // www.biuman.com/test/before/test'
});
Var comment_list_View = Backbone. View. extend ({
Template: _.template(('{tpl-comment-list'{.html ()),
Initialize: function (){
This. model. bind ("change", this. render, this );
},
Events :{
},
Render: function (){
Attributes (this.el).html (this. template (this. model. toJSON ()));
Return this;
}
});
Var comment_item_View = Backbone. View. extend ({
Initialize: function (){
This. model. bind ('reset', this. render, this); // The model here is a set.
Var self = this;
This. model. bind ("add", function (item ){
$ (Self. el). append (new comment_list_View ({model: item}). render (). el );
});
},
Render: function (eventName ){
// The model here is a set
_. Each (this. model. models, function (item ){
$ (This. el). append (new comment_list_View ({model: item}). render (). el );
},
This );
Return this;
}
});
// Router
Var AppRouter = Backbone. Router. extend ({
Routes :{
"": "List ",
"Comment/: id": "comment"
},
Initialize: function (){
},
List: function (){
If (typeof this. index_collection = 'undefined '){
This. index_collection = new index_Collection ();
This. index_item_view = new index_item_View ({
Model: this. index_collection // The imported index_collection collection.
});
Var self = this;
This. index_collection.fetch ({
Success: function (collection, resp ){
// Console. dir (collection. models );
}
}); // Fetch bind the rest event first
} Else {
This. index_item_view = new index_item_View ({
Model: this. index_collection
});
}
Parameters ('{content'{.html (this. index_item_view.render (). el );
},
Comment: function (id ){
This. comment_collection = new comment_Collection ();
This. comment_item_view = new comment_item_View ({
Model: this. comment_collection // input set
});
Var self = this;
This. comment_collection.fetch ({
Url: 'http: // www.biuman.com/test/before/test2/'your ID,
Success: function (collection, resp ){
$ ('# Content'). append (new comment_add_View (). render (). el)
}
}); // Fetch bind the rest event first
Condition ('{content'{.html (this. comment_item_view.render (). el );
}
});
Var app = new AppRouter ();
Backbone. history. start ();
});