使用BackBone建立一个应用程序结构

依赖

 backbone依赖jquery/Zepto,underScore

创建项目的目录结构

1 lib/: 用于存放第三方库文件的目录,包括bcakbone、underscore、jquery
2 js/: 用于存放项目中用到的Js文件,包括main等
3 index.html

实例


    $(document).ready(function() {
    
    //model 模型
    var InvoiceItemModel = Backbone.Model.extend({
        defaults:{
            price:0,
            quantity:0
        },

        calculateAmount: function(){
            return this.get('price') * this.get('quantity');
        }

    });

    //View 模型
    var PreviewInvoiceItemView = Backbone.View.extend({
        // 下文中的\用于连接字符串
        template:_.template('\
                price:<%= price%>.\
                Qunatity:<%= quantity%>.\
                Amount:<%= amount%>.\
            '),
        render:function(){
            var html = this.template({
                price:this.model.get('price'),
                quantity:this.model.get('quantity'),
                amount:this.model.calculateAmount()
            });
            $(this.el).html(html);
        }
    });

    //启动初始化
    var invoiceItemModel = new InvoiceItemModel({
        price:2,
        quantity:3
    });

    var previewInvoiceItemView = new PreviewInvoiceItemView({
        //使用这种方式绑定view与model
        model:invoiceItemModel,
        el:'body'
    });

    previewInvoiceItemView.render();
});

关于路由

继承于Router,定义routes来确定区分不同的

    var Workspace = Backbone.Router.extend({
        routes:{
            '':'invoiceList',
            'invoice':'invoiceList'
        },
        invoiceList:function(){
            var invoiceListView = new InvoiceListView({
                el:'body'
            });
            invoiceListView.render();
        }
    });


    var InvoiceListView = Backbone.View.extend({
        render:function(){
            document.write('123456');
        }
    })


    new Workspace();
    Backbone.history.start();
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,269评论 25 708
  • 路由是实现模块间解耦的一个有效工具。如果要进行组件化开发,路由是必不可少的一部分。目前iOS上绝大部分的路由工具都...
    黑超熊猫zuik阅读 3,972评论 8 52
  • 说起身边很熟悉,很重要的人,我便想起了我三年级认识的一个人,她是我最好的朋友。她本人长得不错,一身高雅的气质,因为...
    百合花张馨文阅读 363评论 0 0
  • 树木丛生 溪流潺潺 逆流而上 踮起脚尖好难 虽然你知道没踮起脚尖是不可能成功 可是要先活着 小鱼只能在下游慢慢的跟...
    枫叶末鹭阅读 109评论 0 0