2

I am trying to override onload function of document and Image in ClojureScript. I think that set! should be possible to do it, but i am not getting any success. Relevant code is as follows :

(defn load-image [img-path]
  (let [img (js/Image.)]
    (do (set! (.-src img) img-path)
        img)))

(defn add-img-canvas [img-path width height]
  (let [img (load-image img-path)]
    (set! (.-onload img) 
          (fn [] ;; This function is never called.
            (let [canvas (get-scaled-canvas img width height)]
              (do (pr-str canvas)
                  (swap! game-state :canvas canvas)))))))

(defn hello-world []
  (let [count (atom 1)]
    (fn []
      [:div 
       [:h1 (:text @game-state)]
       [:div (do (swap! count inc) (str "count is " @count))]
       [:canvas (:canvas @game-state)]])))

(reagent/render-component [hello-world]
                          (. js/document (getElementById "app")))

(set! (.-onload js/document) 
      (fn [] ;; This function is also never called.
        (add-img-canvas (:img-src game-state) 100 130)))

;;(. js/document onload)

Anonymous functions in add-img-canvas is not getting called. What am i doing wrong ?

Ashish Negi
  • 5,193
  • 8
  • 51
  • 95

1 Answers1

0

I think it may be down to the difference between document.onload vs window.onload. The latter does work as expected.

See this for more details between the two.

ducky
  • 1,113
  • 1
  • 11
  • 23
  • ok.. thanks would try that.. Also can you suggest something about `(set! (.-onload img)` i.e. image load. It is also not firing. – Ashish Negi Jan 12 '16 at 07:17
  • 1
    Regarding img, you may want to do an onload before attaching the src. See http://fragged.org/preloading-images-using-javascript-the-right-way-and-without-frameworks_744.html – ducky Jan 12 '16 at 10:58
  • @AshishNegi did you find a solution? – mrchaarlie Jul 11 '16 at 20:45
  • 1
    @mrcharlie i donot remember exactly.. but `window.onload` will work and also above comment by ducky was also helpful. i guess i ended up doing: https://github.com/ashishnegi/phogame/blob/master/src/cljs/phogame/core.cljs#L194 – Ashish Negi Jul 12 '16 at 13:07