IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> RequireJS和Backbone -> 正文阅读

[JavaScript知识库]RequireJS和Backbone

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 }
    ]
});
  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-11-24 07:51:19  更:2021-11-24 07:52:18 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/21 3:43:08-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码