zoukankan      html  css  js  c++  java
  • Backbone学习笔记

    Collection

    Collection可以看成是Model的集合。以下是一个集合的例子:

    var Song = Backbone.Model.extend({
      defaults: {
        name: "Not specified",
        artist: "Not specified"
      },
          initialize: function(){
              console.log("Music is the answer");
          }
    });
    
    var Album = Backbone.Collection.extend({
      model: Song
    });
    
    var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
    var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
    var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });
    
    var myAlbum = new Album([ song1, song2, song3]);
    console.log( myAlbum.models ); // [song1, song2, song3]

    Router

    Backbone.Router担任了一部分Controller的工作,他能将特定的URL或锚点与一个特定的方法绑定。

    var AppRouter = Backbone.Router.extend({
        routes : {
            '' : 'main',
            'topic' : 'renderList',
            'topic/:id' : 'renderDetail',
            '*error' : 'renderError'
        },
        main : function() {
            console.log('应用入口方法');
        },
        renderList : function() {
            console.log('渲染列表方法');
        },
        renderDetail : function(id) {
            console.log('渲染详情方法, id为: ' + id);
        },
        renderError : function(error) {
            console.log('URL错误, 错误信息: ' + error);
        }
    });
    
    var router = new AppRouter();
    Backbone.history.start();

    将例子中的代码复制到你的页面中。假设你的页面地址为http://localhost/index.html,请依次访问下面的地址,并注意控制台的输出结果: 

    • http://localhost/index.html // 输出:应用入口方法
    • http://localhost/index.html#topic // 输出:渲染列表方法
    • http://localhost/index.html#topic/1023 // 输出:渲染详情方法, id为:1023
    • http://localhost/index.html#about // 输出:URL错误, 错误信息: about

      然后再使用浏览器的“前进”、“返回”等按钮进行切换,你会看到当你的URL切换时,控制台输出了对应的结果,说明它已经调用了相应的方法。而在进行这些操时,页面并没有刷新。这个例子很好地解决了我们在一开始所说的两个问题。

    参考:

    http://yujianshenbing.iteye.com/blog/1749831

  • 相关阅读:
    case when then 中判断null的方法
    在SELECT的时候,加入一列固定值
    拿到iframe页面里面的变量及元素的方法
    datatables 多一列报错Cannot read property 'sWidth' of undefined(…)/少一列报错Cannot read property 'style' of undefined(…)
    MySQL 显示表字段及注释等信息
    MYSQL escape用法--转义
    MyBatis insert操作返回主键
    Java关键字final、static使用总结
    数据库往表中插入数据报错
    洛谷 题解 P1287 【盒子与球】
  • 原文地址:https://www.cnblogs.com/dawn/p/5033267.html
Copyright © 2011-2022 走看看