使用jquery.on函数向闭包中的多个动态元素添加事件侦听器,单击

时间:2017-05-07 05:25:03

标签: javascript jquery closures onclicklistener

我正在尝试向动态创建的li添加一个click事件监听器,以便它们彼此独立工作(当前,当您单击其中一个时,所有三个都会激活)。我看到的每个解决方案都涉及一个闭包,我认为我正在做,但我猜不是。此外,视图不断更新模型数组中的最后一个元素,我无法弄清楚原因。非常感谢任何帮助。



$(document).ready(function() {

  //Data displayed in the view
  var model = {
    carOnDisplay: null,
    listOfCars: [{
        numClicks: 0,
        carName: "Challenger",
        color: 'grey'
      },
      {
        numClicks: 0,
        carName: "Charger",
        color: 'blue'
      },
      {
        numClicks: 0,
        carName: "Mustang",
        color: 'orange'
      },
    ]
  };

  var controller = {

    init: function() {
      // set the default car to be displayed
      model.carOnDisplay = model.listOfCars[0];
      carView.init();
      carListView.init();
    },

    getListOfCars: function() {
      return model.listOfCars;
    },

    setCurrentCar: function(car) {
      model.carOnDisplay = car;
    },

    getCurrentCar: function() {
      return model.carOnDisplay;
    },

    incrementClicks: function() {

      model.carOnDisplay.numClicks++;
      carView.render();

    }
  };

  var carView = {
    init: function() {
      // cached DOM
      this.car = $('#car');
      this.name = $('h3.carName');
      this.clicks = $('h4.clicks');
      // add click listeners to car
      this.car.click(function() {
        controller.incrementClicks();
      });
      this.render();
    },
    render: function() {
      var currentCar = controller.getCurrentCar();
      this.car.css('background-color', currentCar.color);
      this.name.html(currentCar.carName);
      this.clicks.html(currentCar.numClicks);
    }
  };

  var carListView = {
    init: function() {
      // cache DOM elements
      this.carList = $('#carList');
      this.render();
    },

    render: function() {
      //  this.links = $('#carList').getElementsByTagName('li');
      var car = controller.getListOfCars(),
        currentCar = controller.getCurrentCar();




      for (var i = 0; i < car.length; i++) {
        var carNow = car[i];

        $('#carList').append("<li>" + carNow.carName + "</li>");
        $('#carList').on('click', one());

        //     // controller.setCurrentCar(carNow);
        //     // carView.render();

      };

      function one() {
        return function(event) {
          controller.setCurrentCar(carNow);
          carView.render();
        }
      }
    }
  } // end of carListView
  controller.init();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-3">
    <ul id="carList">

    </ul>
  </div>
  <div id="content" class="col-9">
    <div id="car" class="col-4">
      <h3 class="carName">x</h3>
      <h4 class="clicks"></h4>
    </div>
  </div>

</div>
&#13;
&#13;
&#13;

0 个答案:

没有答案