import consumer from "./consumer" const count_channel = consumer.subscriptions.create("CountChannel", { 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 console.log(data) if (data.update !== undefined) { if ($("[data-count-id='" + data.update.id + "']").length) this.update(data.update) else this.create(data.update) } 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() }, 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 }) } }, }); $(document).on('turbo:load', function() { $("[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")) }); })