• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

RequireJS和Backbone

武飞扬头像
草木红
帮助1

RequireJS API中文版: https://blog.csdn.net/sanxian_li/article/details/39394097
Require.js下载地址:https://github.com/requirejs
text.js 下载地址:https://github.com/requirejs/text
requirejs加载css:https://segmentfault.com/a/1190000002390643

(一) 使用 RequireJS 编写 AMD 模块

1. define()定义模块

define(model_id,[dependencies], module-factory-or-object);

model_id:通常只有在非AMD格式工具使用时才定义(边界情况也可能有用到)。当该参数不提供时,我们称该模块为匿名模块(anonymous)。使用匿名模块时,RequireJS要使用匿名模块的文件路径作为模块id(module id),因此应该在 define() 调用时省略模块id,以应用 DRY(Don’t Repeat Yourself, 不要重复自己)格言。

dependencies:参数时一个数组,代表该模块所依赖的其他模块,第三个参数可以时用于实例化该模块的可执行函数,也可以是一个对象。

module-factory-or-object: 模块的实现,或者一个JavaScript对象。

(二) RequireJS入门

1.加载require.js文件与主模块

在HTML中通过在<script>标签里添加data-main属性,指定网页程序的主模块(整个网页的入口代码main.js)。此时,RequireJS将自动加载main.js。其中main.js 可以简写为app

  • html文件:
    <!-- 同步方式加载require.js -->
    <script data-main="main.js" src="require.js"></script>
    
    <!-- 异步方式加载require.js 。IE只支持defer,所以把defer也写上。main.js可以简写为main -->
    <script data-main="main" src="require.js" defer async="true" ></script>
    

2. RequireJS配置

在data-main属性上定义的JavaScript主文件里,可以配置RequireJS要加载的剩余脚本。可以通过调用require.config并传入一个对象来达到这一目的。

  • baseUrl:基础路径(可选),默认从该路径下加载所有的文件,一般设置为主模块(main.js)所在的文件夹所在目录
  • paths:文件相对于baseUrl所在的路径 文件的最终路径为 baseUrl paths
  • shim: 垫片(可选),加载不支持AMD的库
  • 满足以下条件,则不会以 baseUrl paths 的方式加载文件,而是直接根据文件路径加载文件(相对于当前HTML文档的脚本):
    • 如果不想 以".js"结尾;
    • 以"/"开头;
    • 包含URL协议,如"http:"、“https:”
    require.config({
    	baseUrl:'',  
    	paths:{}, 
    	shim: {}
    })
    

3. RequireJS里的Shims

并不是每个库都支持AMD,Underscore、Backbone都不支持,在shim中可以对不支持AMD的库进行配置。jQuery(低版本不支持)是支持AMD的所以不需要在shim中定义。

shim配置仅设置了代码的依赖关系,想要实际加载shim指定的或涉及的模块,仍然需要一个常规的require/define调用。设置shim本身不会触发代码的加载。

require.config({
    baseUrl: '',
    paths: {},
    shim: {
        underscore: { //载入underscore.js文件,.js可以省略
            exports: '_' // 告诉RequireJS,underscore.js创建一个叫做 _ 的全局对象,而不是定义一个模块
        },
        backbone: {
            deps: [//定义backbone所需的依赖,应在backbone.js之前加载
                'jquery',
                'underscore'
            ],
            exports: 'Backbone'
        }
    },
})
学新通

(三) RequireJS 和 Text 插件

requireJS有一个特殊的插件叫text.js,用于加载依赖的文本文件。
使用步骤:

  • (1) 下载 text.js 插件
  • (2) 在RequireJS配置项中引入 text.js 插件。
    require.config({
    	paths: {
    		text: 'libs/text'
    	}
    })
    
  • (3) 当 text! 前缀用于依赖项时,RequireJS将自动加载该 text 插件,并将依赖文件转换为一个文本资源。将加载的文本资源作为模板来用。
    require(['js/app', 'text!templates/mainView.html'],
    	function(app, mainView){
    		var AppView = Backbone.View.extend({
    	      el: '.box',
    	      template: _.template(mainView),
    	      render: function () {
    	        this.html(this.template({title: '这是标题'}));
    	      },
    	    });
    	
    		return AppView;
    	}
    )
    
    mainView.html
    <label><%= title %></label>
    

(四) Require.js/Backbone示例

学新通

1.目录结构

学新通

2.index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    ul,
    li {
      list-style: none;
      margin: 0;
      padding: 0;
    }

    .info-box,
    .shopping-list {
      display: table;
      clear: both;
    }

    .add-shopping,
    .search-shopping {
      border: 1px solid #ddd;
      width: 280px;
      float: left;
      margin-right: 20px;
      padding: 10px 20px;
    }

    .shopping-list {
      margin-top: 20px;
    }

    .shopping-list li {
      float: left;
      border: 1px solid #ddd;
      padding: 0 15px 15px;
      margin-right: 20px;
    }
  </style>
</head>

<body>
  <div class="info-box">
    <div class="add-shopping">
      <label>商品名称:<input type="text" class="title"></label><br>
      <label>商品价格:<input type="text" class="price"></label><br>
      <br>
      <button class="add-btn">添加</button>
    </div>

    <div class="search-shopping">
      <label>商品价格大于:<input type="text" class="search-price"></label>
      <br><br><br>
      <button class="search-btn" class="search">搜索</button>
      <button class="clear-search">清除搜索</button>
    </div>
  </div>

  <ul class="shopping-list">

  </ul>


  <script data-main="./js/main" src="./js/lib/require.js"></script>
</body>
</html>
学新通

3.js/collections/goods.js

模型集合

define(['underscore','backbone', 'models/good'], function (_, Backbone, Good) {
  'use strict';
  var GoodsCollection = Backbone.Collection.extend({
    model: Good,
    //title已经有的数量
    titleNumber: function(title){
     return this.where({'title': title}).length;
    },
    filterGoods: function(price){
      var filtered = _.filter(this.models, function(item) {
        return item.get("price") > price;
      });

      return filtered;
    }
  });


  return new GoodsCollection();
});
学新通

4.js/models/good.js

模型

define(['backbone'], function (Backbone) {
  'use strict';
  var GoodModel = Backbone.Model.extend({
    defaults: {
      title: '',
      price:0
    },
    initialize: function () {
      this.on('invalid', function (model, error) {
        alert(error);
      });
    },
    validate: function (attrs) {
      if (!$.trim(attrs.title)) {
        return '商品名称不能为空';
      }

      if (!$.trim(attrs.price) || attrs.price <= 0 ||  attrs.price !==  attrs.price) {
        return '商品价格为大于0的数字';
      }
    }
  });

  return GoodModel;
});
学新通

5.js/templates/good-tpl.html

模型视图的模板

<p><%= title %></p>
<strong><%= price %></strong>

6.js/views/app.js

主要的功能文件

define(['jquery', 'underscore', 'backbone', 'collections/goods', 'models/good', 'views/GoodView', 'common'], function ($, _, Backbone, goods, Good, GoodView, common) {
  var AppView = Backbone.View.extend({
    el: 'body',
    initialize: function () {
      this.listenTo(goods, 'add', this.addGoodView);

      goods.add(common); //添加默认商品
    },
    events: {
      'click .add-btn': 'addGood',
      'click .search-btn': 'searchGoods',
      'click .clear-search': 'clearSearch'
    },
    addGood: function () {
      var title = this.$('.title').val();
      var price = Number(this.$('.price').val());

      var good = new Good();

      //校验商品信息
      if (good.set({
          'title': title,
          'price': price
        }, {
          validate: true
        })) {
        if (goods.titleNumber(title)) {
          alert('商品名称已经存在');
          return false;
        }
        goods.add(good);
        this.$('.title').val('');
        this.$('.price').val('');
      }
    },
    searchGoods: function () {
      var price = Number(this.$('.search-price').val());
      var filtered = goods.filterGoods(price);
      var self = this;

      this.$('.shopping-list').empty();

      _.each(filtered, function (item) {
        self.addGoodView(item);
      })
    },
    clearSearch: function () {
      this.$('.search-price').val('');
      var self = this;
      this.$('.shopping-list').empty();

      _.each(goods.models, function (item) {
        self.addGoodView(item);
      })
    },
    addGoodView: function (model) {
      var goodView = new GoodView({
        model: model
      });

      var view = goodView.render().el;
      this.$('.shopping-list').append(view);
    }
  });

  return AppView;
})
学新通

7.js/views/goodView.js

模板模型

define(['underscore', 'backbone', 'text!templates/good-tpl.html'], function (_, Backbone, goodTpl) {
  'use strict';
  var GoodView = Backbone.View.extend({
    tagName: 'li',
    template: _.template(goodTpl),
    render: function () {
      this.$el.append(this.template(this.model.toJSON()));
      return this;
    },
  });

  return GoodView;
});

8. js/common.js

全局变量

define([], function(require, factory) {
  'use strict';
  
    return [
      { title: "Macbook Air", price: 799 },
      { title: "Macbook Pro", price: 999 },
      { title: "The new iPad", price: 399 },
      { title: "Magic Mouse", price: 50 },
      { title: "Cinema Display", price: 799 }
    ]
});

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbgkcc
系列文章
更多 icon
同类精品
更多 icon
继续加载