Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/kevinbatdorf/alpine-observe-other-components

A lightweight observer function for Alpine.js that lets you monitor state on other Alpine components
https://github.com/kevinbatdorf/alpine-observe-other-components

Last synced: 2 months ago
JSON representation

A lightweight observer function for Alpine.js that lets you monitor state on other Alpine components

Awesome Lists containing this project

README

        

# Alpine — Observe Other Components
A lightweight observer function for Alpine.js that lets you monitor state on other Alpine components, including parent components.

![GitHub file size in bytes](https://img.shields.io/github/size/kevinbatdorf/alpine-observe-other-components/dist/index.js?label=minified&style=flat-square)
![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/kevinbatdorf/alpine-observe-other-components?label=version&style=flat-square)

## About

Useful when you want to watch updates on child elements, or when you need to watch state in general.

#### Watch everything
Add `x-alpine-observe` attribute with the function name. Each component with this attribute will watch all other components and run your function every time.
```html


```
[Demo](https://codepen.io/KevinBatdorf/pen/c7439ba7c47cb84464cf9409e289641c)

#### Watch only specific components
Add `x-alpine-observe` attribute with an object to specify a selector. Only components with this selector will be monitored for changes. Note that changes occur on initial load so the example below will first show `1`, not `0`.
```html

Watched

Not watched


```
[Demo](https://codepen.io/KevinBatdorf/pen/1100d05938a0a2ed51f2e391c6b8cf68)

#### Watch parent components
Similar to above, you can scope the child to only watch the parent for changes.
```html



Parent:


Nested




```
[Demo](https://codepen.io/KevinBatdorf/pen/1c6c57ed30a79ca26a934a702d3f6095)

## Installation

Include the following `` tag in the `<head>` of your document (before Alpine):

```html
<script src="https://cdn.jsdelivr.net/gh/kevinbatdorf/alpine-observe-other-components@latest/dist/index.js">
```

### Manual

If you wish to create your own bundle:

```bash
npm install kevinbatdorf/alpine-observe-other-components --save
```

Then add the following to your script:

```javascript
import 'alpine-observe-other-components'
import 'alpinejs'
```

## License

Copyright (c) 2020 Kevin Batdorf

Licensed under the MIT license, see [LICENSE.md](LICENSE.md) for details.