zoukankan      html  css  js  c++  java
  • backbone实例01

      backbonejs往简单说,就是一前端MVC框架,适合用于单页面、复杂的前端逻辑。

      直接上代码,里面都有相关注释,重点是理解清楚view、collection、model这三者如何关联调用。

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
     5     <title>backbone实例01</title>
     6 </head>
     7 <body>
     8     <input type="text" id="add">
     9     <ul id="man-list">
    10     </ul>
    11     <script src="vendor/zepto.js"></script>
    12     <script src="vendor/underscore.js"></script>
    13     <script src="vendor/backbone.js"></script>
    14     <script>
    15     (function ($) {
    16         //定义model
    17         var People = Backbone.Model.extend({
    18                defaults: {
    19                    name: null
    20                }
    21         });
    22 
    23         //定义Collection
    24         var Peoples = Backbone.Collection.extend({
    25             model: People,//关联上了相关model
    26             initialize: function(options) {
    27                 this.bind('add',options.view.show);//这里事件监听关键
    28             }
    29         });
    30 
    31         //定义view
    32         var AppView = Backbone.View.extend({
    33             el: $("body"),
    34             initialize: function() {
    35                 this.peoples = new Peoples({view: this});//关联上集合
    36             },
    37             events: {
    38                 'keypress #add': 'addMan'
    39             },
    40             addMan: function(e) {
    41                 var key = e.which;
    42                 if(key !== 13) return;
    43                 var name = $(e.target).val();
    44                 var people = new People({name:name});
    45                 this.peoples.add(people);//添加model到集合,与此同时会触发集合中的监听方法
    46             },
    47             show: function(model){//集合调用view中的方法,并能将集合中的model传递过来
    48                 var template = "<li>你们好,我是"+model.get('name')+",请多多关照!</li>";
    49                 $('#man-list').append(template);
    50                 $('#add').val('');
    51             }
    52         });
    53 
    54         new AppView();
    55     })(Zepto);
    56     </script>
    57 </body>
    58 </html>

      该例中,入口是Appview,其初始化时就关联了一collection,在该collection中关联上了model,并添加了‘add’监听方法,该方法在往集合中添加model时出发,这里在出发时会调用view中的相关方法渲染页面。

      backbone实例02。。。。。进行中。。。。。

  • 相关阅读:
    [转]xna 3.1 to xna 4.0
    office 2010 激活信息查看
    Windows 8 Release Preview下载地址
    常用书籍推荐与下载地址
    禁用Windows7脱机文件的方法
    [转]DEM数据和影像数据下载汇总
    打工是最愚蠢的投资——李嘉诚在深圳大梅沙演讲
    j截图Code
    BYTE与_int64转换
    英语中of和for用法有什么区别?
  • 原文地址:https://www.cnblogs.com/justTheOne-bin/p/3713398.html
Copyright © 2011-2022 走看看