讓我們用Backbone.js來寫一個HelloWorld程式。

來源:互聯網
上載者:User

建立一個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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.