让我们用Backbone.js来写一个HelloWorld程序。

新建一个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();


  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值