Backbone.js Hello World program instance
- 2020-06-19 09:43:08
- OfStack
Create a new api. php file with the following contents:
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, other haml, jade or underscore templates are also ok.)
Content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script type="text/javascript" src="./jquery.min.js"></script>
<script type="text/javascript" src="./underscore.min.js"></script>
<script type="text/javascript" src="./backbone.min.js"></script>
<script type="text/javascript" src="./mustache.min.js"></script>
<script type="text/javascript" src="./custom.js"></script>
</HEAD>
<BODY>
<p><script id="hello-container-template" type="text/template"></p><p><div>{{name}} says: {{message}} </div></p><p></script></p>
</BODY>
</HTML>
Create a new ES22en. js file with the following contents:
// This is a 1 That runs view / control / model The global class
var App = {
Models: {},
Views: {},
Controllers: {},
Collections: {},
initialize: function() {
new App.Controllers.Routes();
Backbone.history.start() // To drive everything Backbone The program, Backbone.history.start() It's a must.
}
};
App.Models.Hello = Backbone.Model.extend({
url: function() {
return '/api.php'; // Get the background address of the data.
},
initialize: function() {
this.set({'message':'hello world'}); // The front-end definition 1 a message Fields, name Fields are supplied by the back end.
}
});
App.Views.Hello = Backbone.View.extend({
el: $("body"),
template: $("#<span style="font-family: monospace; white-space: pre; ">hello-container-template</span>").html(),
initialize: function(options){
this.options = options;
this.bind('change', this.render);
this.model = this.options.model;
},
render: function(){ // render Method with only two goals: fill this.el To return to this For chain operation.
$(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 Driven routing
},
hello : function() {
// new 1 The new page is rendered according to the model after the model has successfully updated the content requested by the back end
var helloModel = new App.Models.Hello;
helloModel.fetch({
success: function(model){
var helloView = new App.Views.Hello({model: model});
helloView.trigger('change');
}
})
}});
App.initialize();