Skip to content

Instantly share code, notes, and snippets.

@dimusik
Last active March 19, 2020 18:14
Show Gist options
  • Save dimusik/9f63048201c257051193521559a0691e to your computer and use it in GitHub Desktop.
Save dimusik/9f63048201c257051193521559a0691e to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
use Laravel\Nova\Element;
trait BroadcastsField
{
public function broadcastTo($broadcastChannel): Element
{
return $this->withMeta([
'broadcastTo' => $broadcastChannel
]);
}
}
export const BroadcastsField = {
mounted() {
if (typeof this.initializeComponent === "function") {
this.initializeComponent()
}
if (this.selectedResourceId) {
this.broadcastValue(this.selectedResourceId);
} else if (this.field.value) {
this.broadcastValue(this.field.value);
}
},
methods: {
broadcastValue: function (value) {
if (Array.isArray(this.field.broadcastTo)) {
this.field.broadcastTo.forEach(el => this.broadcast(el, value))
} else {
this.broadcast(this.field.broadcastTo, value)
}
},
setFieldAndMessage(el) {
const value = 'value' in el ? el.value : el.target.value
this.broadcastValue(value);
this.value = value;
},
broadcast(channel, value) {
Nova.$emit(channel, {
field_name: this.field.attribute,
value: value
});
},
selectResource(resource) {
this.selectedResource = resource
this.setFieldAndMessage(resource)
}
}
}
<?php
namespace App\Traits;
trait ListensToBroadcast
{
protected $listensTo;
public $calculateFunction;
public function setRoute($url)
{
return $this->withMeta(['route' => $url]);
}
public function listensTo($channel)
{
$this->listensTo = $channel;
return $this;
}
public function calculateWith(callable $calculateFunction)
{
$this->calculateFunction = $calculateFunction;
return $this;
}
public function jsonSerialize()
{
return array_merge([
'listensTo' => $this->listensTo
], parent::jsonSerialize());
}
}
import _ from "lodash";
import { Errors } from 'form-backend-validation';
export const ListensToBroadcasts = {
created() {
Nova.$on(this.field.listensTo, this.messageReceived);
this.field_values["resourceId"] = parseInt(this.resourceId);
},
data: () => ({
calculating: false,
field_values: {}
}),
methods: {
messageReceived(message) {
this.field_values[message.field_name] = message.value;
this.calculateValue();
},
calculateValue: _.debounce(function () {
this.errors = new Errors();
this.calculating = true;
Nova.request()
.post(
this.field.route,
this.field_values
)
.then(response => {
this.value = response.data.value;
this.calculating = false;
this.broadcastValue(response.data.value);
})
.catch(error => {
this.calculating = false;
let errors = [];
for (let [key, value] of Object.entries(error.response.data.errors)) {
errors.push(`${value.join(', ')}`)
}
this.errors = new Errors(
{ [this.field.attribute]: [errors.join("<br>")] }
);
});
}, 500),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment