Created
May 8, 2015 15:03
-
-
Save aappddeevv/8cd4f1c54abad5a237b6 to your computer and use it in GitHub Desktop.
direct translation of virtual-dom example into scalajs, does not use functional idioms at all :-)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tutorial.webapp | |
import language._ | |
import scala.scalajs.js | |
import scala.scalajs.js.JSApp | |
import scala.scalajs.js.annotation.JSName | |
import org.scalajs.dom | |
import org.scalajs.jquery.jQuery | |
import dom.document | |
import scala.scalajs.js.timers._ | |
import concurrent.duration._ | |
trait VNode extends js.Object { | |
def tagName: String = js.native | |
def key: js.UndefOr[String] = js.native | |
def namespace: js.UndefOr[String] = js.native | |
def count: Int = js.native | |
def hasWidgets: Boolean = js.native | |
def hasThunks: Boolean = js.native | |
def hooks: js.UndefOr[js.Dictionary[js.Any]] = js.native | |
def children: js.Array[VNode] = js.native | |
def properties: js.Dictionary[js.Any] = js.native | |
} | |
trait Patch extends js.Object | |
@JSName("virtualDom") | |
object VirtualDom extends js.Object { | |
def create(node: VNode, opts: js.UndefOr[js.Object] = js.undefined): dom.raw.HTMLElement = js.native | |
def diff(lhs: VNode, rhs: VNode): Patch = js.native | |
def h(tagName: String, properties: js.UndefOr[js.Dictionary[js.Any]] = js.undefined, | |
children: js.UndefOr[js.Array[js.Any]] = js.undefined): VNode = js.native | |
def patch(rootNode: dom.raw.Node, patches: Patch): dom.raw.HTMLElement = js.native | |
} | |
object TutorialApp extends JSApp { | |
import VirtualDom._ | |
def render(count: Int) = { | |
h("div", | |
properties = js.Dictionary[js.Any](("style", js.Dictionary[js.Any]( | |
("textAlign", "center"), | |
("lineHeight", (100 + count).toString + "px"), | |
("border", "1px solid red"), | |
("width", (100 + count).toString + "px"), | |
("height", (100 + count).toString + "px")))), | |
children = js.Array[js.Any](count.toString)) | |
} | |
def main(): Unit = { | |
var count = 0 | |
var tree = render(count) | |
var rootNode = create(tree) | |
document.body.appendChild(rootNode) | |
val cancel = setInterval(1000) { | |
count += 1 | |
val newTree = render(count) | |
var patches = diff(tree, newTree) | |
rootNode = patch(rootNode, patches) | |
tree = newTree | |
} | |
setTimeout(10 seconds)(clearInterval(cancel)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment