2017-07-26 94 views
1

我正在Rails的一家小書店工作。用戶可以爲個別書籍撰寫評論,並將其添加到產品頁面。我想使用ActionCable將新評論添加到頁面,以便它始終處於最新狀態,並在爲當前處於同一頁面上的其他用戶添加評論時顯示一個小警報通知。ActionCable頻道訂閱不起作用,因爲頻道方法未執行

因此,我想根據產品的ID爲每個產品設置單獨的渠道。當用戶打開產品頁面時,她應該訂閱相應的頻道。

爲了達到這個目的,我試圖調用一個名爲listen的方法,我添加到ProductChannel類中,每當通過調用JS中的App.product.perform('listen', {product_id: 1})加載新站點時。但問題是,雖然perform被調用,listen永遠不會執行。我在做什麼錯誤或誤解?提前致謝!

內容javascript/channels/prouduct.coffee

內容的 channels/product_channel.rb
App.product = App.cable.subscriptions.create "ProductChannel", 
    connected:() -> 
     return 

    disconnected: -> 
     # Called when the subscription has been terminated by the server 
     return 

    received: (data) -> 
     # Called when there's incoming data on the websocket for this channel 
     console.log("there is data incoming so lets show the alert") 
     $(".alert.alert-info").show() 
     return 

    listen_to_comments: -> 
     @perform "listen", product_id: $("[data-product-id]").data("product-id") 

$(document).on 'turbolinks:load', -> 
    App.product.listen_to_comments() 
    return 

class ProductChannel < ApplicationCable::Channel 
    def subscribed 
    end 

    def unsubscribed 
    end 

    def listen(data) 
    stop_all_streams 
    stream_for data["product_id"] 
    end 
end 
+0

它可能是turbolinks,當你把App.product.listen_to_comments放入js控制檯時會發生什麼? – Snake

+0

它按預期返回方法。我剛剛發現,提交審閱時不規則地調用listen方法,這不是正確的時刻。我無法理解它。 – drdn5

+0

我懷疑turbolinks:負載發射多次。試穿: i = 0; $(document).on'turbolinks:load', - > console.log i ++ – Snake

回答

0

連接對象已被實例化:

module ApplicationCable 
    class Connection < ActionCable::Connection::Base 
    identified_by :current_user 

    def connect 
     self.current_user = find_verified_user 
     logger.add_tags current_user.name 
    end 

    def disconnect 
     # Any cleanup work needed when the cable connection is cut. 
    end 

    protected 
     def find_verified_user 
     if current_user = User.find_by_identity cookies.signed[:identity_id] 
      current_user 
     else 
      reject_unauthorized_connection 
     end 
     end 
    end 
end 

然後,你需要broadcast_to的@product

class ProductChannel < ApplicationCable::Channel 
    def subscribed 
    @product = Product.find(params[:product_id]) 
    end 

    def unsubscribed 
    stop_all_streams 
    end 

    def listen(data) 
    stream_for @product 
    ProductsChannel.broadcast_to(@product) 
    end 
end 
+0

非常感謝您的輸入,Snake。但我確實實例化了連接對象並設置了廣播。我將問題簡化爲@perform()方法,該方法在第一次調用時返回false,但在每次進一步調用時返回true。我爲它創建了一個新問題,它更具體:https://stackoverflow.com/questions/45336276/actioncable-channel-subscription-method-perform-returns-false-on-first-call-of – drdn5