循环依赖

a) Use the Inline Require Syntax 使用内联Require语法

//user.js
define([], function () {
   var cart = require('cart'); //using this style to work around circular reference
   var numItemsInCart = cart.items.length;
   //logic to initialize user's cart icon continues here...
});

缺点:

  • 限制自动测试
  • 依赖顺序不确定

b) Utilize the Publish-Subcribe Pattern 使用发布者/订阅者模式 c) Pass Data into the Constructor 从构造器传递数据 d) Unify Closely Related Modules 统一相关联的模块,有可能是设计问题 e) Pass a Function Reference into the Constructor 从构造器传递一个方法引用 f) Move Logic/Data to One Side 把数据/逻辑移至一侧 g) Create a Business Object/Service 创建一个逻辑对象/服务

7 Ways to Handle Circular Dependencies in RequireJS

results matching ""

    No results matching ""