Skip to content

Commit

Permalink
Add URLHashDemo w/ window.onhashchange closure (#288)
Browse files Browse the repository at this point in the history
* Add `URLHashDemo` w/ `window.onhashchange` closure

Resolves #284

* Assign `.undefined` in HashState.deinit
  • Loading branch information
MaxDesiatov authored Oct 6, 2020
1 parent a631d18 commit dbd1ee4
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions Sources/TokamakDemo/TokamakDemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ struct TokamakDemoView: View {
#if os(WASI)
Section(header: Text("TokamakDOM")) {
NavItem("DOM reference", destination: DOMRefDemo())
NavItem("URL hash changes", destination: URLHashDemo())
}
#endif
}
Expand Down
52 changes: 52 additions & 0 deletions Sources/TokamakDemo/URLHashDemo.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright 2020 Tokamak contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import JavaScriptKit
import TokamakDOM

private let location = JSObject.global.location.object!
private let window = JSObject.global.window.object!

private final class HashState: ObservableObject {
var onHashChange: JSClosure!

@Published var currentHash = location.hash.string!

init() {
let onHashChange = JSClosure { [weak self] _ in
self?.currentHash = location.hash.string!
}

window.onhashchange = .function(onHashChange)
self.onHashChange = onHashChange
}

deinit {
window.onhashchange = .undefined
onHashChange.release()
}
}

struct URLHashDemo: View {
@StateObject private var hashState = HashState()

var body: some View {
VStack {
Button("Assign random location.hash") {
location.hash = .string("\(Int.random(in: 0...1000))")
}
Text("Current location.hash is \(hashState.currentHash)")
}
}
}

0 comments on commit dbd1ee4

Please sign in to comment.