2023-02-04 14:22:05 +01:00
|
|
|
import consumer from "./consumer"
|
|
|
|
|
2023-02-05 21:01:07 +01:00
|
|
|
const count_channel = consumer.subscriptions.create("CountChannel", {
|
2023-02-04 14:22:05 +01:00
|
|
|
connected() {
|
|
|
|
// Called when the subscription is ready for use on the server
|
|
|
|
console.warn("Connected to CountChannel.");
|
|
|
|
},
|
|
|
|
|
|
|
|
disconnected() {
|
|
|
|
// Called when the subscription has been terminated by the server
|
|
|
|
},
|
|
|
|
|
|
|
|
received(data) {
|
|
|
|
// Called when there's incoming data on the websocket for this channel
|
2023-02-05 21:01:07 +01:00
|
|
|
console.log(data)
|
2023-02-05 23:10:37 +01:00
|
|
|
if (data.update !== undefined) {
|
|
|
|
if ($("[data-count-id='" + data.update.id + "']").length)
|
|
|
|
this.update(data.update)
|
|
|
|
else
|
|
|
|
this.create(data.update)
|
|
|
|
}
|
2023-02-05 21:01:07 +01:00
|
|
|
|
|
|
|
if (data.destroy !== undefined)
|
|
|
|
this.destroy(data.destroy)
|
|
|
|
},
|
|
|
|
|
|
|
|
update(data) {
|
|
|
|
$("[data-count-id='"+ data.id + "'] .count").text(data.count)
|
|
|
|
$("[data-count-id='"+ data.id + "'] .name").text(data.name)
|
|
|
|
},
|
|
|
|
|
|
|
|
destroy(data) {
|
|
|
|
$("[data-count-id='"+ data + "']").remove()
|
|
|
|
},
|
2023-02-05 23:10:37 +01:00
|
|
|
|
|
|
|
create(data) {
|
|
|
|
let created = $("#template").clone()
|
|
|
|
created.attr("data-count-id", data.id)
|
|
|
|
created.find(".name").text(data.name)
|
|
|
|
created.find(".count").text(data.count)
|
|
|
|
created.find(".minus").click(function () {
|
|
|
|
count_channel.minus_one(data.id)
|
|
|
|
})
|
|
|
|
created.find(".plus").click(function () {
|
|
|
|
count_channel.plus_one(data.id)
|
|
|
|
})
|
|
|
|
created.find(".edit").attr("href", data.edit_link)
|
|
|
|
created.removeClass("d-none")
|
|
|
|
$("#count-list").append(created)
|
|
|
|
},
|
|
|
|
|
|
|
|
minus_one(id) {
|
|
|
|
if (count_channel !== undefined && !count_channel.consumer.connection.disconnected) {
|
|
|
|
count_channel.perform("minus_one", { "id": id })
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
plus_one(id) {
|
|
|
|
if (count_channel !== undefined && !count_channel.consumer.connection.disconnected) {
|
|
|
|
count_channel.perform("plus_one", { "id": id })
|
|
|
|
}
|
|
|
|
},
|
2023-02-04 14:22:05 +01:00
|
|
|
});
|
2023-02-05 21:01:07 +01:00
|
|
|
|
|
|
|
$(document).on('turbo:load', function() {
|
2023-02-05 23:10:37 +01:00
|
|
|
$("[data-count-id] .minus").click(function () {
|
|
|
|
count_channel.minus_one($(this).parents("[data-count-id]").attr("data-count-id"))
|
|
|
|
});
|
|
|
|
$("[data-count-id] .plus").click(function () {
|
|
|
|
count_channel.plus_one($(this).parents("[data-count-id]").attr("data-count-id"))
|
|
|
|
});
|
2023-02-05 21:01:07 +01:00
|
|
|
})
|