DIV CSS 佈局教程網

用 RequireJS + Backbone 重構移動端圖片查看器
編輯:關於JavaScript     

本文既是對舊版圖片查看器的補充,也是近期學習 RequireJS 與 Backbone 的一次實戰落地,希望能給同路人一點參考。前文可參閱《製作手機使用的網頁圖片查看器》。

頁面結構

require 的引入是重點,data-main 指明了主函數所在文件:

<!doctype html>
<html lang="zh-cn">
<head>
<title>webapp 圖片查看器</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<script src="https://cdn.file1.goodid.com/static/js/require.min.js" data-main="/static/js/pic/main"></script>
</head>
<body>
<section class="index">
<h1>手機網頁圖片查看器</h1>
<figure class="download">
<a>其它文件</a>
<a url="https://static.bootcss.com/www/assets/img/opencdn.png">圖片a</a>
<a url="https://static.bootcss.com/www/assets/img/buttons.png">圖片b</a>
<a>其它文件</a>
<a url="https://static.bootcss.com/www/assets/img/gruntjs.png">圖片c</a>
<a url="https://static.bootcss.com/www/assets/img/lesscss.png">圖片d</a>
</figure>
</section>
</body>
</html>

require.js 加載完畢後自動載入 main.js,樣式部分不再佔篇幅。

模板部分

三個模板分別對應對話框、位置指示與單張圖片,直接寫進 HTML:

<script id="dialog_tmpl" type="text/template">
<section></section>
<figure id="swipe"><ul></ul></figure>
<footer>
<span id="l">左旋</span>
<span id="r">右旋</span>
<span id="pos" index="<%=index %>" length="<%=length %>"><%=index %>/<%=length %></span>
</footer>
</script>
<script id="pos_tmpl" type="text/template">
<span id="pos" index="<%=index %>" length="<%=length %>"><%=index %>/<%=length %></span>
</script>
<script id="item_tmpl" type="text/template">
<img src="<%=src %>" width="<%=width %>" height="<%=height %>" url="<%=url %>" />
</script>

主函數 main.js

require.config({
  paths: {
    jquery: 'https://cdn.file1.goodid.com/static/js/zepto.min',
    fastclick: 'https://cdn.file1.goodid.com/static/js/fastclick.min',
    underscore: 'https://cdn.file1.goodid.com/static/js/underscore.min',
    backbone: 'https://cdn.file1.goodid.com/static/js/backbone.min',
    swipe: 'https://cdn.file1.goodid.com/static/js/swipe.min'
  },
  shim: {
    jquery: { exports: '$' },
    fastclick: { deps: ['jquery'] }
  }
});
require(['underscore', 'backbone', 'fastclick'], function () {
  FastClick.attach(document.body);
  require(['./view/global'], function (Global) {
    var global = new Global;
  });
});

paths 定義各模塊路徑;shim 重新解析了 jquery 模塊,並為 fastclick(一款消除 300ms 點擊延遲、提升觸摸體驗的微型插件)聲明依賴 jquery。隨後依次加載 underscore、backbone、jquery、fastclick,最後載入全局控制視圖並實例化。

全局控制視圖 global.js

define(['model/pic', 'collection/set', 'view/imager'], function (Pic, Set, Imager) {
  var set = new Set;
  var global = Backbone.View.extend({
    el: 'body',
    data: $('.download [url]'),
    events: { 'click .download [url]': 'open' },
    open: function (model) {
      var url = $(model.target).attr('url');
      var index = this.data.index($(model.target));
      var length = this.data.length;
      var total = new Pic.total({ index: index + 1, length: length });
      var dialog = new Imager.dialog({ model: total });
      $(this.el).prepend(dialog.render().el);
      this.collect();
      this.list();
      this.swipe(index);
      this.loading(url, index);
    },
    collect: function () {
      if (set.length > 0) return false;
      this.data.each(function () {
        var item = new Pic.item({ name: $(this).text(), url: $(this).attr('url') });
        set.add(item);
      });
    },
    list: function () {
      var obj = $('#swipe ul');
      set.each(function (model) {
        var list = new Imager.list({ model: model });
        obj.append(list.render().el);
      });
    },
    swipe: function (index) {
      require(['swipe'], function () {
        var swipe = new Imager.swipe;
        swipe.render(index).el;
      });
    },
    loading: function (url, index) {
      var item = new Pic.item({ url: url });
      var loading = new Imager.loading({ model: item, el: $('#swipe li').eq(index).find('img') });
      loading.render();
    }
  });
  return global;
});

依次載入數據模型 pic、集合 set、視圖 imager 並實例化一個集合。全局視圖中定義了五個方法:繪製查看器的 open、添加模型的 collect、繪製列表的 list、繪製滑動效果的 swipe、繪製加載動畫的 loading。

渲染視圖 imager.js

define(['model/pic'], function (Pic) {
  var imager = Object;

  imager.dialog = Backbone.View.extend({
    initialize: function () { _.bindAll(this, 'render'); },
    tagName: 'section',
    className: 'dialog',
    template: _.template($('#dialog_tmpl').html()),
    events: { 'click #l, #r': 'turn' },
    render: function () {
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
    },
    turn: function (model) {
      var index = parseInt($('#pos').attr('index')) - 1;
      var obj = $('#swipe li').eq(index).find('img');
      var deg = parseInt(obj.attr('deg') ? obj.attr('deg') : 0);
      var type = model.target.id;
      if (type && type == 'l') deg -= 90;
      else if (type && type == 'r') deg += 90;
      if (deg > 360) deg -= 360;
      else if (deg < -360) deg += 360;
      obj.css({ '-webkit-transform': 'rotate(' + deg + 'deg)' }).attr({ 'deg': deg });
    }
  });

  imager.list = Backbone.View.extend({
    initialize: function () { _.bindAll(this, 'render'); },
    tagName: 'li',
    template: _.template($('#item_tmpl').html()),
    events: { 'click img': 'close' },
    render: function () {
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
    },
    close: function () { $('.dialog').remove(); }
  });

  imager.fix = Backbone.View.extend({
    initialize: function () { _.bindAll(this, 'render'); },
    el: '#pos',
    template: _.template($('#pos_tmpl').html()),
    render: function () {
      $(this.el).replaceWith(this.template(this.model.toJSON()));
      $('#swipe [deg]').removeAttr('deg').removeAttr('style');
      return this;
    }
  });

  imager.loading = Backbone.View.extend({
    initialize: function () { _.bindAll(this, 'render'); },
    template: _.template('<img src="<%=url %>" />'),
    render: function () {
      var obj = $(this.el);
      var html = this.template(this.model.toJSON());
      var img = new Image();
      img.src = this.model.attributes.url;
      img.onload = function () { obj.replaceWith(html); };
      return this;
    }
  });

  imager.swipe = Backbone.View.extend({
    initialize: function () { _.bindAll(this, 'render'); },
    render: function (index) {
      var obj = document.getElementById('swipe');
      window.mySwipe = Swipe(obj, {
        startSlide: index,
        continuous: false,
        disableScroll: true,
        callback: function (index, element) {
          var length = $('#pos').attr('length');
          var total = new Pic.total({ index: index + 1, length: length });
          var fix = new imager.fix({ model: total });
          fix.render();
          var url = $(element).find('img').attr('url');
          if (!url || url.length == 0) return false;
          var item = new Pic.item({ url: url });
          var loading = new imager.loading({ model: item, el: $(element).find('img') });
          loading.render();
        }
      });
      return this;
    }
  });
  return imager;
});

模型與集合

// model/pic.js
define(function () {
  var pic = Object;
  pic.total = Backbone.Model.extend({ defaults: { index: 1, length: 1 } });
  pic.item = Backbone.Model.extend({
    defaults: {
      name: '圖片加載中...',
      src: 'https://cdn.file1.goodid.com/static/images/loading.gif',
      url: '',
      width: 40,
      height: 40
    }
  });
  return pic;
});
// collection/set.js
define(['model/pic'], function (Pic) {
  var set = Backbone.Collection.extend({ model: Pic.item });
  return set;
});

模塊化之後,程序結構清晰了許多;按需加載讓文件執行順序完全可控;MVC 拆分(此處 C 尚未用上)則讓數據層與視圖層各歸其位,混亂大幅減少。

以上就是本文的全部內容,希望對大家的學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved