Home > Web Front-end > JS Tutorial > body text

Hello World program example of Backbone.js_Others

WBOY
Release: 2016-05-16 15:53:50
Original
1259 people have browsed it

Create a new api.php file with content:

Copy code The code is as follows:

header('Content-Type: application/json; charset=utf-8');
die(json_encode(array('name'=>'tom')));

Create a new index.html file. (Backbone is based on jquery and underscore. We use Mustache for template parsing. Of course, you can also use other haml, jade, or templates in underscore)

Content:

Copy code The code is as follows:




New Document










Create a new custom.js file with content:

Copy code The code is as follows:

// This is a global class that manages views/controls/models
var App = {
Models: {},
Views: {},
Controllers: {},
Collections: {},
initialize: function() {
new App.Controllers.Routes();
Backbone.history.start() // To drive all Backbone programs, Backbone.history.start() is necessary.
}
};
App.Models.Hello = Backbone.Model.extend({
url: function() {
            return '/api.php'; // Get the backend address of the data.
},
initialize: function() {
This.set({'message':'hello world'}); // The front end defines a message field, and the name field is provided by the back end.
}
});
App.Views.Hello = Backbone.View.extend({
el: $("body"),
template: $("#hello-container-template").html(),
initialize: function(options){
this.options = options;
this.bind('change', this.render);
this.model = this.options.model;
},
render: function(){ // The render method has only two goals: filling this.el and returning this for chain operations.
$(this.el).html(Mustache.to_html($(this.el).template,this.model.toJSON()) );
return this
}
});
App.Controllers.Routes = Backbone.Controller.extend({
routes: {
"!/hello" : "hello",//Use #!/hello to drive routing
},
hello : function() {
//Create a new model. After the model successfully requests updated content from the backend, it will render a new page based on the model
var helloModel = new App.Models.Hello;
helloModel.fetch({
success: function(model){
var helloView = new App.Views.Hello({model: model});
helloView.trigger('change');
}
})
}});
App.initialize();
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template