网络编程 
首页 > 网络编程 > 浏览文章

Backbone.js的Hello World程序实例

(编辑:jimmy 日期: 2025/12/27 浏览:3 次 )

新建一个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="/UploadFiles/2021-04-02/jquery.min.js"> <script type="text/javascript" src="/UploadFiles/2021-04-02/underscore.min.js"> <script type="text/javascript" src="/UploadFiles/2021-04-02/backbone.min.js"> <script type="text/javascript" src="/UploadFiles/2021-04-02/mustache.min.js"> <script type="text/javascript" src="/UploadFiles/2021-04-02/custom.js">  </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();

上一篇:使用ngView配合AngularJS应用实现动画效果的方法
下一篇:使用AngularJS处理单选框和复选框的简单方法
一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap