亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Backbone.js的Hello World程序實例

 更新時間:2015年06月19日 10:54:29   投稿:junjie  
這篇文章主要介紹了Backbone.js的Hello World程序實例,本文給出后端PHP通信、前臺HTML、和Backbone.js 代碼,需要的朋友可以參考下

新建一個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>
  <p><script&nbsp;id="hello-container-template"&nbsp;type="text/template"></p><p><div>{{name}}&nbsp;says:&nbsp;{{message}}&nbsp;</div></p><p></script></p>
 </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: $("#<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方法,目標只有兩個:填充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();

相關文章

最新評論