JSFiddle - React, Tailwind, and code Playground

by tea4two

JavaScript

var people = {
	// 名前の保管庫
	people: ['will', 'steve'],
  
  // イニシャライズ
  init: function() {
  	// DOMのキャッシュ		
   	this.cacheDom();
    
    // イベントのバインド
    this.bindEvent();
    
    // HTMLへの反映
    this.render();
  },
  
  // DOMのキャッシュ
  cacheDom: function() {
  	this.$el = $('#peopleModule');
    this.$button = this.$el.find('button');
    this.$input = this.$el.find('input');
    this.$ul = this.$el.find('ul');
    this.template = this.$el.find('#people-template').html();
  },
  
  // クリックの際のイベントのバインド
  bindEvent: function() {
  	// 1. 追加イベント
  	// これはよくない(2つの操作が入っている。クリックとクリック後のアクションの2つ)
  	// this.$button.on('click', function(){...});
    
    // 人を追加するというアクションは別のメソッドとする
    // ※bind(this)は addPersonの部分で解説
    this.$button.on('click', this.addPerson.bind(this));
    
    // 2. 削除イベント
    this.$ul.on('click', 'i.del', this.deletePerson.bind(this));
  },
  
  // HTMLへの反映
  render: function() {
  	var data = {
    	people: this.people,
    };
    this.$ul.html(Mustache.render(this.template, data));
  },
  
  // 名前の追加
  addPerson: function(value) {
  	// このthisはbindEventから呼び出されるthisである
    // 且つ、clickイベントの際に引き起こされている
    // ここでのthisは何に変わるかと言うと this.$buttonである。
    // なので addPerson を行う際は peopleオブジェクトにbindする必要がある。
    // valueはaddPersonが外部から直接呼ばれた際の対応
  	this.people.push(value || this.$input.val());
    this.render();
    this.$input.val(''); //インプットを空に
  },
  
  // 名前の削除
  deletePerson: function(event) {
		var $remove = $(event.target).closest('li');
    var index = this.$ul.find('li').index($remove);
    
    // 名前の保管庫より削除する
    this.people.splice(index, 1);
    this.render();
  }
 
};

people.init();