天天看点

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