建立一個api.php檔案,內容:
header('Content-Type: application/json; charset=utf-8');die(json_encode(array('name'=>'tom')));
建立一個index.html檔案。(backbone基於jquery、underscore,我們使用Mustache來做模板解析,當然用其他的haml、jade,或者underscore裡面的模板也都是可以)
內容:
<!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> <script id="hello-container-template" type="text/template">
<div>{{name}} says: {{message}} </div>
</script>
</BODY></HTML>
建立一個custom.js檔案,內容:
// 這是一個管理著 視圖/控制/模型 的全域類var App = { Models: {},Views: {},Controllers: {},Collections: {},initialize: function() {new App.Controllers.Routes(); Backbone.history.start() // 要驅動所有的Backbone程式,Backbone.history.start()是必須的。 }};App.Models.Hello = Backbone.Model.extend({ url: function() { return '/api.php'; // 獲得資料的後台地址。 }, initialize: function() { this.set({'message':'hello world'}); // 前端定義一個message欄位,name欄位由後端提供。 }});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(){ // render方法,目標只有兩個:填充this.el,返回this以便鏈式操作。$(this.el).html(Mustache.to_html($(this.el).template,this.model.toJSON()) );return this}});App.Controllers.Routes = Backbone.Controller.extend({routes: {"!/hello" : "hello",//使用#!/hello驅動路由},hello : function() {//建立一個模型,模型向後端請求更新內容成功後根據模型渲染新頁面var helloModel = new App.Models.Hello;helloModel.fetch({success: function(model){var helloView = new App.Views.Hello({model: model});helloView.trigger('change');}})}});App.initialize();