Что означает .parent, когда ставится после переменной с! (напр. (! myVariable.parent) - PullRequest
0 голосов
/ 24 августа 2018

Я довольно новичок в JavaScript и внешнем кодировании в целом.Я работаю над кодом и пытаюсь понять все в коде, чтобы я мог изменить свои потребности.

Есть функция, которая выходит:

function checkTiles() { // function for the check button

  for (var i = 0; i < dragTiles.length; i++) { // iterate through all the draggable tiles (a variable declared earlier)

    var tile = dragTiles[i]; // variable for this iteration

    if (!tile.parent) {
      continue;
    }

//does more stuff..

}

(комментарии для меня, чтобы лучше понять).

Я пытаюсь понять, что за строка "если(! tile.parent) "делает.Из того, что я прочитал, «родитель» относится к родительскому окну?Так что, эта строка говорит что-то вроде «если переменная тайла (перетаскиваемые тайлы) не равна родительскому окну» ??

Это не имеет большого смысла для меня.Вот ссылка на кодовую ручку, над которой я работаю, если поможет ее просмотр в контексте - https://codepen.io/kbeats/pen/eLpawv

Обратите внимание, что я не писал эту ручку кода, пока не очень хорош в кодировании.

Любая помощь очень ценится, спасибо!

Ответы [ 2 ]

0 голосов
/ 24 августа 2018
if (!tile.parent) {
      continue;
   }

проверка по ! означает, что проверка tile.parent является ложным условием.

здесь tile - это объект, и вы проверяете, нет ли у него свойства с именем parent.

EDIT

Я прошел ручку, чтобы увидеть, что держит этот массив dragTiles. так что у нас там есть

var dragTiles = Array.prototype.map.call(dragElements, createDragTile);

и dragElements - это

var dragElements = document.querySelectorAll(".drag-tile");

здесь вы можете видеть dragElements - это просто dom-узлы, которые имеют класс .drag-title

но у элементов dom нет свойства parent. поэтому вам нужно проверить определение createDragTile, которое

function createDragTile(element, index) {

  TweenLite.set(element, { 
    left: pad, 
    top: pad + index * (pad + element.offsetHeight) 
  });

  var draggable = new Draggable(element, { 
    bounds: ".board",
    onDragStart: onDragStart,
    onDrag: onDrag,
    onDragEnd: onDragEnd
  });
  // here we are declaring the tile object. with custom property parent
  var tile = { 
    element: element,
    parent: null,  // this is your parent. author is setting it for the tile. its a custom object. not refering to global window or anything.
    value: element.dataset.value 
  };

  function onDragStart() {}

  function onDrag() {
    // here is the info of parent property         
    var parent = tile.parent; // parent variable equals the parent property of tile varaible(which is set to NULL in the variable TILE above) SO, PARENT = NULL if drag tile isn't on a drop tile, if it IS then parent = the DROP TILE DIV

    if (parent) { // so if the parent is NULL, then look for the hit Test (cause the drag tile isn't on anything yet)

      if (this.hitTest(parent.element, threshold)) { // if THIS (the item that iniatied the function, the tile being dragged) overlaps with THE PARENT ELEMENT, so parent = null and element = element ?? 

        // exit the function
        // tile is still hitting parent, so no need to proceed any further.
        return; // exit and END THE FUNCTION HERE IF it is hitting the threshold
      }

      // tile is no longer hitting parent, so clear any references between the two
      parent = tile.parent = parent.child = null;  // if it's not hitting the threshold CLEAR ANY REFERENCES WHAT IS THIS ???????
    }

    for (var i = 0; i < dropTiles.length; i++) { // iterate through all the drop tiles

      var dropTile = dropTiles[i]; // variable for above iteration

      if (dropTile.child) { // child is NULL until a drag tile is on Top of if, so if the dropTile IS NULL then continue, if it doesn't have anything on it. 

        // continue to next loop iteration
        // drop tile already has a child, so no need to proceed any further
        continue;
      }

      if (this.hitTest(dropTile.element, threshold)) { // if the draggable hits a drop tile threshold

        // we hit an empty drop tile, so link the two together and exit the function
        tile.parent = dropTile; // here we are assigning the tile.parent to be DROP TILE 
        dropTile.child = tile; // here we are assigning the dropTile child to be TILE
        element.classList.add("hitting"); // add the class HITTING
        return;
      }
    }

    // if we made it this far, we're not hitting an empty drop tile
    element.classList.remove("hitting");
  }

  function onDragEnd() {

Из этой функции я понял, что если .parent, являющееся пользовательским свойством в этой структуре данных, равно null, то элемент не перетаскивается в местоположение. это все еще в своем первоначальном положении. если плитка находится в положении выпадения, ее .parent становится выпадающей плиткой. это не относится ни к какому глобальному объекту или окну. он просто содержит ссылку на плитку, куда вы можете бросить элемент, это может быть null или dom node ссылка

0 голосов
/ 24 августа 2018

Вы можете думать о ! как о выражении, которое отрицает что-то. Javascript имеет следующие значения «falsey» - «false», что означает, что они равны false в булевых проверках:

false
undefined
null
NaN
0
"" или ''

Выражение if (!tile.parent) проверяет, равно ли title.parent одному из указанных выше значений Falsey. Если так, продолжайте. Если нет - условие не выполняется, и выполнение кода продолжается далее в функции.

...