Hello World program instance of Backbone. js, backbone. jshello
Create an api. php file with the following content:
Copy codeThe Code is as follows:
Header ('content-Type: application/json; charset = UTF-8 ');
Die (json_encode (array ('name' => 'Tom ')));
Create an index.html file. (Based on jquery and underscore, backbone uses Mustache for template parsing. Of course, other haml, jade, or templates in underscore are also supported)
Content:
Copy codeThe Code is as follows:
<! 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> <div >{{ name }} says: {message }}</div> </p> </script> </p>
</BODY>
</HTML>
Create a custom. js file with the following content:
Copy codeThe Code is as follows:
// This is a global class that manages views, controls, and 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 required.
}
};
App. Models. Hello = Backbone. Model. extend ({
Url: function (){
Return '/api. php'; // The background address for obtaining data.
},
Initialize: function (){
This. set ({'message': 'Hello world'}); // The frontend defines a message field. The name field is provided by the backend.
}
});
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, and return this for chained 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 (){
// Create a new model. After the model requests the updated content to the backend, it renders the 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 ();