瀏覽代碼

Merge pull request #574 from thiagomajesk/patch-1

Make more clear how to use $dispatch with sibling nodes
Caleb Porzio 5 年之前
父節點
當前提交
f377c93254
共有 1 個文件被更改,包括 33 次插入0 次删除
  1. 33 0
      README.md

+ 33 - 0
README.md

@@ -589,6 +589,39 @@ If you need to access $event inside of a JavaScript function you can pass it in
 </div>
 ```
 
+**Note on Event Propagation**
+
+Notice that, because of [event bubbling](https://en.wikipedia.org/wiki/Event_bubbling), when you need to capture events dispatched from nodes that are under the same nesting hierarchy, you'll need to use the [`.window`](https://github.com/alpinejs/alpine#x-on) modifier:
+
+**Example:**
+
+```html
+<div>
+    <span @custom-event="console.log($event.detail.foo)"></span>
+    <button @click="$dispatch('custom-event', { foo: 'bar' })">
+<div>
+```
+
+> This won't work because when `custom-event` is dispatched, it'll propagate to its common ancestor, the `div`.
+
+**Dispatching to Components**
+
+You can also take advantage of the previous technique to make your components talk to each other:
+
+**Example:**
+
+```html
+<div @foo-event.window="console.log($event.detail.foo)">
+    <button @click="$dispatch('bar-event', { bar: 'bar' })">
+    <!-- When clicked, will console.log "foo" -->
+</div>
+
+<div @bar-event.window="console.log($event.detail.bar)">
+    <button @click="$dispatch('foo-event', { foo: 'foo' })">
+    <!-- When clicked, will console.log "bar" -->
+</div>
+```
+
 `$dispatch` is a shortcut for creating a `CustomEvent` and dispatching it using `.dispatchEvent()` internally. There are lots of good use cases for passing data around and between components using custom events. [Read here](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events) for more information on the underlying `CustomEvent` system in browsers.
 
 You will notice that any data passed as the second parameter to `$dispatch('some-event', { some: 'data' })`, becomes available through the new events "detail" property: `$event.detail.some`. Attaching custom event data to the `.detail` property is standard practice for `CustomEvent`s in browsers. [Read here](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) for more info.