浏览代码

Enable $watch for arrays

Simone Todaro 5 年之前
父节点
当前提交
fd2997c804
共有 1 个文件被更改,包括 21 次插入0 次删除
  1. 21 0
      src/component.js

+ 21 - 0
src/component.js

@@ -114,9 +114,30 @@ export default class Component {
         }, 0)
 
         return wrap(data, (target, key) => {
+            const isArray = Array.isArray(target)
             if (self.watchers[key]) {
                 // If there's a watcher for this specific key, run it.
                 self.watchers[key].forEach(callback => callback(target[key]))
+            } else if (isArray) {
+                // Array are special cases, if any of the element changes, we consider the array as mutated.
+                // Key is not relevant since it's going to be the item index
+                Object.keys(self.watchers)
+                    .forEach(fullDotNotationKey => {
+                        let dotNotationParts = fullDotNotationKey.split('.')
+
+                        // Ignore length mutations since they would result in duplicate calls
+                        // For example, when calling push, we would get a mutation for the item
+                        // and a second mutation for the length property
+                        if (key === 'length') return
+
+                        dotNotationParts.reduce((comparisonData, part) => {
+                            if (Object.is(target, comparisonData[part])) {
+                                // Run the watchers.
+                                self.watchers[fullDotNotationKey].forEach(callback => callback(target))
+                            }
+                            return comparisonData[part]
+                        }, self.getUnobservedData())
+                    })
             } else {
                 // Let's walk through the watchers with "dot-notation" (foo.bar) and see
                 // if this mutation fits any of them.