简体   繁体   中英

ClojureScript, Figwheel, Devcards, Race Condition

Here is my minimal failure case.

(ns hello
  (:require-macros [devcards.core :as dc])
  (:require [reagent.core :as r]
            [devcards.core :as dc]
            [gamma.api :as g]
            [gamma.program :as p]
            [goog.dom :as gdom]
            [goog.webgl :as ggl]))


(defn main []
  (let [canvas (.getElementById js/document "webgl")
        gl (.getContext canvas "webgl")] ;; *** THIS LINE ***
    (.clearColor gl 0.0 0.0 0.0 1.0)
    (.clear gl gl.COLOR_BUFFER_BIT)))


(dc/defcard-rg canvas-example
  [:div
   [:canvas {:width 600
             :height 600
             :id "webgl"}]])


(main)

Here's what happens when I load this up in figwheel/devcard.

  1. First time loading page: "Cannot read property 'getContext' of null" on * THIS LINE * . This is because the devcard canvas hasn't been setup yet.

  2. If I make a pointless change and save the file, the code reloads and works fine. This is because the devcard canvas HAS been setup.

  3. It's clear this is a race condition between (a) when (main) runs and (b) when devcard's :canvas is setup.

  4. How do I fix this? Ideally, I want to tag something to the canvas saying "run the main function after this ..."

Okay, I figured this out.

The simplest solution (ie does not involve hacking devcard / reagent) is to just have a separate cljs/go thread check every 50ms to see whether the element exists, and if so, exec the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM