I
I
Ivan Ivanov2019-08-14 14:28:28
JavaScript
Ivan Ivanov, 2019-08-14 14:28:28

Why is data not being sent through the eventBus?

Good afternoon, tell me please. I wrote a calendar with events display and now I want to make it possible to add an event on a specific day. When I click on the add button, a function is triggered openAddEvent()in the EventsDays component in which the bus passes the current day, month and year to the ModalWindowAdd component in the addEvent function. I tried to output to the console all the data that I passed and it showed me that this data is not there. And because of this, I cannot add the newly created event on the correct date. Tell me where I made a mistake in passing information in the event bus.
Full code on GitHub A
screenshot of the console that shows what was passed to the addEvent function:
5d53efdc18ec3607712366.png
The component where the events are located, from where the data is sent to the addEvent function.

<template>
        <transition :name="nameOfClass" >
          <div :key="currentPage" class="fade_wrapper">
            <div v-for="(week, i) in getCalendar" class="d_day">
            <li v-for="day in week" 
                class="li_day"
                v-bind:class="{   'currentDay': currentDayOnCalendar(i, day), }" >  
              <img  src="src/assets/plus.png" 
                  width="16px" 
                  height="16px"
                  v-show="addPlus(i, day)" 
                  v-on:click="openAddEvent(day)"> 
              <div class="day" 
                   v-bind:class="{  'grey': isAnotherMonth(i, day),
                                    'red': weekEndDayFunction(i, day) }">{{ day }}</div>
              <div  v-for="event in buildEvents(i, day)" 
                    class="event"
                    v-bind:class="{  'eventBrown': eventBrown(event), 
                                     'eventPurple': eventPurple(event),
                                     'eventOrange': eventOrange(event),
                                     'eventBlue': eventBlue(event) }"
                    v-on:click="openModalDetail(event)">{{ event }}
              </div>
            </li>
          </div>
        </div>
      </transition>
</template>

<script>
  import { bus } from './../main.js'
export default {
  data(){
    return{
      date: new Date(),
      isActive: true,
      options: [
        { text: 'Встреча', value: '8' },
        { text: 'День Рождения', value: '4' },
        { text: 'Праздник', value: '1' },
        { text: 'Другое', value: '16' }
      ],
      year: Number,
      currentPage: Number,
      nameOfClass: '',
      modalWindowAdd: false,
    }
  },
  created(){
  	this.year = this.date.getFullYear();
    this.currentPage = this.date.getMonth();
  	bus.$on('sendYear', data => {
  		this.year = data
  	});
  	bus.$on('sendMonth', data => {
  		this.currentPage = data
  	});
  	bus.$on('sendNameOfClass', data => {
  		this.nameOfClass = data
  	});
  },
  computed: {
    getCalendar(){
      return this.buildCalendar();
    },
    eventsData() {
    return this.$store.state.eventData;
  }
  },
  methods: {
    openAddEvent(dayNumber){
    	this.modalWindowAdd = true;
    	bus.$emit('changeModalWindowAdd', this.modalWindowAdd);
        bus.$emit('sendDayWhenAddEvent', dayNumber);
        bus.$emit('sendYear', this.year);
    	bus.$emit('sendMonth', this.currentPage);
    },
    buildEvents(weekIndex, dayNumber){
      let arrOfEvents = this.eventsData.events;
      const events = [];
       for(let z = 0; z < arrOfEvents.length; z++){
        let dataStartOfEvent = arrOfEvents[z].starts_at;
        let getStartDataOfEvent = new Date(dataStartOfEvent);
        let dataEndOfEvent = arrOfEvents[z].ends_at;
        let getEndDataOfEvent = new Date(dataEndOfEvent);
        let memo = arrOfEvents[z].memo;
        if(getStartDataOfEvent.getDate() == getEndDataOfEvent.getDate()){
          if(dayNumber == getStartDataOfEvent.getDate() &&
            this.currentPage == getStartDataOfEvent.getMonth() &&
            this.year == getStartDataOfEvent.getFullYear() &&
            !this.isAnotherMonth(weekIndex, dayNumber)){
              events.push(memo);
              continue;
          }
        }else if(getStartDataOfEvent.getDate() != getEndDataOfEvent.getDate() &&
            !this.isAnotherMonth(weekIndex, dayNumber)){
          for(let b = getStartDataOfEvent.getDate(); b <= this.getLastDayOfMonth(getStartDataOfEvent.getMonth()); b++){
            if(dayNumber === b &&
            this.currentPage == getStartDataOfEvent.getMonth() &&
            this.year == getStartDataOfEvent.getFullYear()){
              events.push(memo);
              continue;
            }
          }
          for(let b = 0; b <= getEndDataOfEvent.getDate(); b++){
            if(dayNumber === b &&
            this.currentPage == getEndDataOfEvent.getMonth() &&
            this.year == getEndDataOfEvent.getFullYear()){
              events.push(memo);
              continue;
            }
          }
        }
      }
      return events;
    },
  }
};
</script>

The component where the addEvent function is located.
<template>
  <div class="underModalWindow">
      <div class="modalWindow">
        <img src="src/assets/x.png" width="20px" height="20px" @click="closeModalAdd">
        <div class="modalWindow_order">Укажите событие которое хотите добавить на выбраную вами дату.</div>
        <div class="modalWindow-input_select">
          <input type="text" placeholder="Место для вашего события" v-model="inputInAddEvent">
          <div>
            <select v-model="selected">
              <option disabled value="">Тип события</option>
              <option v-for="option in options" v-bind:value="option.value">
                {{ option.text }}
              </option>
            </select>
          </div>
        </div>
          <div v-if="textOfError" class="textOfError">Вы обязательно должны указать событие и тип события</div>
        <button v-on:click="addEvent(inputInAddEvent)">Добавить событие</button>
      </div>
    </div>
</template>

<script>
import { mapState } from "vuex";  
import { bus } from './../main.js'
export default {
  data(){
    return{
      date: new Date(),
      inputInAddEvent: '',
      options: [
        { text: 'Встреча', value: '8' },
        { text: 'День Рождения', value: '4' },
        { text: 'Праздник', value: '1' },
        { text: 'Другое', value: '16' }
      ],
      selected: '',
      textOfError: false,
      dayWhenAddEvent: Number,
      year: Number,
      currentPage: Number
    }
  },
  computed: {
    eventsData() {
      return this.$store.state.eventData;
    }
  },
  methods: {
    addEvent(text){
      bus.$on('sendDayWhenAddEvent', data => {
        this.dayWhenAddEvent = data;
      });
      bus.$on('sendYear', data => {
        this.year = data
      });
      bus.$on('sendMonth', data => {
        this.currentPage = data
      });
      console.log(this.dayWhenAddEvent)
      console.log(this.year)
      console.log(this.currentPage)
      if(this.selected == '' || text == ''){
        this.textOfError = true;
      }else if(text != ''){
        this.modalWindowAdd = false;
        bus.$emit('changeModalWindowAdd', this.modalWindowAdd)
        let arrOfEvents = this.eventsData.events;
        let eventObj = {
          "id": Date.now(),
          "starts_at": new Date(this.year, this.currentPage, this.dayWhenAddEvent),
          "ends_at": new Date(this.year, this.currentPage, this.dayWhenAddEvent),
          "memo": text,
          "type": +this.selected
        };
        arrOfEvents.push(eventObj);
        console.log(arrOfEvents[9].ends_at) // дата добавления последнего события
        this.inputInAddEvent = '';
      }
    },
    closeModalAdd(){
      this.modalWindowAdd = false;
      bus.$emit('changeModalWindowAdd', this.modalWindowAdd)
    }
  }
};
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-08-14
@IvanInvanov

You are already using vuex, so drive the data through it.
UPD. Taken from the comments:
"Practice"? You do not need this - you are a beginner, and the event bus has long been deprecated. Why would you want to learn from questionable and outdated practices?
"Mistake"? Mistakes - you have a whole bunch of them.
If we talk about those because of which the observed behavior differs from the expected one, then these are: firstly, passing data before the component instance (window of adding an event) is created; secondly, subscription to events in the dialog box in the handler for clicking on the add button, and not when creating the component.
But besides them, there are other jambs - you do not remove event handlers when the component instance is destroyed; for some reason you are passing the date elements separately; in the calendar subscribe to receive data sent by the calendar.
In general, everything is very, very bad.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question