【问题标题】:Callbacks with Require JS使用 Require JS 的回调
【发布时间】:2015-05-28 22:31:24
【问题描述】:

所以我正在尝试制作两个功能,允许用户将商品从他们的购物车移动到“已保存的购物车”,反之亦然。这些功能依赖于“购物车组项目”模块,该模块还包含按钮点击事件。我的问题是,我不确定如何正确调用这些函数以允许在我当前的 js 文件中发生点击事件。希望有人可以提供帮助!

模块中的事件:

cartGroupItem.prototype.createMoveEvent = function (elem) {
  if (undefined !== elem && null !== elem) {
    var button = elem.querySelector('.cartGroupItem__move');
    if (button !== null) {
      button.addEventListener('click', function (e) {
        ajax('GET',
               '/resources/ajax/cart.aspx?sub=3&Saved=0&Cart_Group_ID='+this.cartGroupId,
          true, {}, function () {
            this.moveToCartCallback();
          }.bind(this), function () {
            this.showErrorDiv();
          }.bind(this));
      }.bind(this));
    }
  }
};

cartGroupItem.prototype.createSaveEvent = function (elem) {
  if (undefined !== elem && null !== elem) {
    var button = elem.querySelector('.cartGroupItem__save');
    if (button !== null) {
      button.addEventListener('click', function (e) {
        ajax('GET',
               '/resources/ajax/cart.aspx?sub=3&Saved=1&Cart_Group_ID='+this.cartGroupId,
          true, {}, this.saveForLaterCallback.bind(this), this.showErrorDiv.bind(this));
      }.bind(this));
    }
  }
};

移动功能:

function moveToSaved(cartGroupId) {
    for (var i = 0, l = activeCartList.length; i < l; i++) {
        if (activeCartList[i].cartGroupId === cartGroupId) {
            activeCartList.remove();
            savedCartList.push(activeCartList[i]);
        }

    }
}

function moveToActive(cartGroupId) {
    for (var i = 0, l = savedCartList.length; i < l; i++) {
        if (savedCartList[i].cartGroupId === cartGroupId) {
            savedCartList.remove();
            activeCartList.push(savedCartList[i]);
        }
    }
}

【问题讨论】:

    标签: javascript require


    【解决方案1】:

    您的Event 模块可能定义了函数cartGroupItem 对吧?

    你需要做的是把这个函数从它的文件传递到你当前的文件,然后“实例化”一个carteGroupItem:

    // In your current JS file
    var myCartGroupItem = new cartGroupItem();
    myCartGroupItem.createMoveEvent();
    myCartGroupItem.createSaveEvent();
    

    我们还需要查看这个函数“构造函数”(定义它的地方),因为它可能需要一些回调作为参数。否则,您可以手动添加它们:

    myCartGroupItem.moveToCartCallback = function() {
      // do what you want when the item is moved to cart
    };
    // Same for the other callbacks
    myCartGroupItem.saveForLaterCallback = function() { ... };
    myCartGroupItem.showErrorDiv = function() { ... };
    

    最后,使用 RequireJS 传递东西的方式是,例如,您的 Event 模块返回 cartGroupItem 所以在您的文件模块中:

    define(['Event'], function(cartGroupItem) {
      // Your code where you can use cartGroupItem
    });
    

    【讨论】:

    • 谢谢!你完美地回答了我的问题。至于实例化该项目,我实际上已经在我的文件中进一步完成了。这是在数据已经通过之后。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2015-10-14
    • 2012-12-02
    • 1970-01-01
    相关资源
    最近更新 更多