天天看點

Backbone案例的初略了解

版權聲明:轉載時請以超連結形式标明文章原始出處和作者資訊及本聲明

http://www.blogbus.com/monw3c-logs/217636180.html

先說一下Backbone的執行順序:

路由(Backbone.Router)-> 模型(Backbone.Model)-> 視圖(Backbone.View)

路由告訴你要去哪裡。

App.Controllers.Routes = Backbone.Router.extend({  
    routes: {  
    "!/hello" : "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');  //綁定change事件
            }
        });
    }
});      

模型告訴該幹些什麼。這裡是去拿資料,set是提供一個設定初始資料

App.Models.Hello = Backbone.Model.extend({  
    url: function() {  
        return '/index/test'; // 獲得資料的背景位址。
    },  
    initialize: function() {  
        this.set({'message':'hello world'}); // 前端定義一個message字段,name字段由後端提供。
    }  
});      

最後你就知道了有什麼了

App.Views.Hello = Backbone.View.extend({  
    el: "body",  //在哪裡顯示
    template: $("#hello-container-template").html(),  //擷取模闆 模闆是用Mustache
    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.template,this.model.toJSON()));
        return this;
    }
});      

上面就是MVC的核心了,下面就是一個管理着"視圖/控制/模型"的全局類

var App = {  
    Models: {},  
    Views: {},  
    Controllers: {},  
    Collections: {},  
    initialize: function() {  
        new App.Controllers.Routes();  
        Backbone.history.start() // 要驅動所有的Backbone程式,Backbone.history.start()是必須的。  
    }  
};      

調用,完事啦。。。

App.initialize();      

原文位址:http://juntype.com/junlab/99.html

轉載于:https://www.cnblogs.com/hushufang/p/3578913.html