【问题标题】:How should I define or reinitialize this variable?我应该如何定义或重新初始化这个变量?
【发布时间】:2017-11-10 14:40:50
【问题描述】:

我有这样的事情:

var menu = (function() {
  var itemContainer = $('#item-container');
  var items = $('.item');

  return {
    countItems: function() {
      //do something with items object.  This does not work.
      console.log('items.length: ' + items.length)
    },
    manipulateItemContainer: function() {
      //do something with itemContainer object. This works fine.
    },
    populate: function() {
      //dynamically create elements with .item class
      var item1 = $('<div/>', {
        class: 'item'
      }).appendTo(itemContainer);
      var item2 = $('<div/>', {
        class: 'item'
      }).appendTo(itemContainer);
      var item3 = $('<div/>', {
        class: 'item'
      }).appendTo(itemContainer);
    },
    addItem: function() {
      var item = $('<div/>', {
        class: 'item'
      }).appendTo(itemContainer);
    }
  }

})();

menu.populate();
menu.countItems();
menu.addItem();
menu.countItems();
.item {
  width: 20px;
  height: 20px;
  display: inline-block;
  background-color: green;
  margin: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item-container">
</div>

在这种情况下,items 为空。我应该如何重新配置​​它来解决这个问题?创建一个init() 函数并在.populate() 的末尾运行它?其他选择?还是我完全错过了其他东西?

【问题讨论】:

    标签: jquery closures


    【解决方案1】:

    由于可用项目的数量是动态的,也许使用函数调用来检索它们会更好:

    var menu = function() {
      var itemContainer = $('#item-container');
    
      function getItems() {
          return $('.item');
      }
    
      return {
        manipulateItems: function() {
          //do something with items object.  This does not work.
          // check if there are any items first
          if (getItems()) {
            // work with items
          }
        },
        manipulateItemContainer: function() {
          //do something with itemContainer object. This works fine.
        },
        populate: function() {
          //dynamically create elements with .item class
        }
      }
    
    }
    

    【讨论】:

    • 这行得通,但是如果我在填充函数之外添加或删除项目怎么办?我更新了问题以添加 .addItem() 方法。
    • 明白了。尝试改用一些私有函数(我更新了我的答案)。这样您每次都能获得最新的可用信息。
    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多