@PlasterTom

Что делает этот код?

Что попадает в переменную "s"? И если не сложно, то по шагам объяснить этот код (Ниже есть пояснения к коду, но они не достаточно ясные для меня).
usersAddedOrRemoved: function(changeRecord) {
    if (changeRecord) {
      changeRecord.indexSplices.forEach(function(s) {
        s.removed.forEach(function(user) {
          console.log(user.name + ' was removed');
        });


Из документации Полимера
Use an array mutation observer to call an observer function whenever an array item is added or deleted using Polymer's array mutation methods. Whenever the array is mutated, the observer receives a change record representing the mutation as a set of array splices.

observers: [
  'usersAddedOrRemoved(users.splices)'
]


Your observer method should accept a single argument. When your observer method is called, it receives a change record of the mutations that occurred on the array. Each change record provides the following property:

indexSplices. The set of changes that occurred to the array, in terms of array indexes. Each indexSplices record contains the following properties:

index. Position where the splice started.
removed. Array of removed items.
addedCount. Number of new items inserted at index.
object: A reference to the array in question.
type: The string literal 'splice'.

Example
Polymer({

  is: 'x-custom',

  properties: {
    users: {
      type: Array,
      value: function() {
        return [];
      }
    }
  },

  observers: [
    'usersAddedOrRemoved(users.splices)'
  ],

  usersAddedOrRemoved: function(changeRecord) {
    if (changeRecord) {
      changeRecord.indexSplices.forEach(function(s) {
        s.removed.forEach(function(user) {
          console.log(user.name + ' was removed');
        });
        for (var i=0; i<s.addedCount; i++) {
          var index = s.index + i;
          var newUser = s.object[index];
          console.log('User ' + newUser.name + ' added at index ' + index);
        }
      }, this);
    }
  },
  ready: function() {
    this.push('users', {name: "Jack Aubrey"});
  },
});
  • Вопрос задан
  • 237 просмотров
Пригласить эксперта
Ответы на вопрос 1
abler98
@abler98
Software Engineer
В observers прописаны все наблюдатели за изменениями в массиве users, таким образом при добавлении/удалении (возможно также при других операциях) элемента массива вызывается метод usersAddedOrRemoved, содержащий в себе информацию об изменениях: indexSplices - массив объектов, в которых есть такие свойства: index, removed, addedCount, object, type.

В данном коде changeRecord.indexSplices.forEach(function(s) { значение s содержит перечисленные выше свойства, т.е. это элемент массива indexSplices (читаем документацию по forEach, если не ясно https://developer.mozilla.org/ru/docs/Web/JavaScri... )
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы