Create a new api.php file with content:
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:
New Document
{{name}} says: {{message}}
Create a new custom.js file with content:
// 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();