• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala document类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中org.scalajs.dom.document的典型用法代码示例。如果您正苦于以下问题:Scala document类的具体用法?Scala document怎么用?Scala document使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了document类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: Statistics

//设置package包名称以及导入依赖的类
package ui

import org.scalajs.dom.document
import org.scalajs.dom.html.{Div, Element, Span}
import ui.helper.HtmlCreator

object Statistics {
  def setField[T](id: String, format: String)(value: Double): Unit = {
    Option(document.getElementById(id))
      .foreach(elem => {
        elem.textContent = format.format(value)
      })

  }

  def setAvgSpeed(avgSpeed: Double): Unit = setField("speed", "%8.5f")(avgSpeed)
  def setStdDev(stdDev: Double): Unit = setField("stddev", "%8.5f")(stdDev)
  def setIteration(iteration: Int): Unit = setField("iteration", "%5.0f")(iteration.toDouble)
  def setCount(vehiclesCount: Int, roadLength: Int): Unit = {
    setField("vehicles-count", "%5.0f")(vehiclesCount.toDouble)
    setField("road-count", "%5.0f")(roadLength.toDouble)
    setField("actual-density", "%5.4f")(vehiclesCount.toDouble / roadLength.toDouble)
  }

  def setupUI(): Element = {
    val container = HtmlCreator.create[Div]("statistics-box")
    container.classList.add("jumbotron")
    container.appendChild(StatBox.createStat("road-count", "Liczba komórek drogi: "))
    container.appendChild(StatBox.createStat("vehicles-count", "Liczba pojazdów: "))
    container.appendChild(StatBox.createStat("actual-density", "Faktyczna g?sto?? pojazdów: "))
    container.appendChild(StatBox.createStat("speed", "?rednia pr?dko??: "))
    container.appendChild(StatBox.createStat("stddev", "Odchylenie standardowe pr?dko?ci: "))
    container.appendChild(StatBox.createStat("iteration", "Iteracja: "))

    container
  }

  object StatBox {
    def createStat(valueName: String, constantText: String): Div = {
      val box = HtmlCreator.create[Div](valueName + "-box")
      val textSpan = HtmlCreator.create[Span]("text-" + valueName)
      textSpan.classList.add("label")
      textSpan.classList.add("label-info")
      textSpan.textContent = constantText
      box.appendChild(textSpan)

      val valueSpan = HtmlCreator.create[Span](valueName)
      valueSpan.textContent = "0"
      box.appendChild(valueSpan)

      box
    }
  }
} 
开发者ID:tlewowski,项目名称:nagel-schreckenberg,代码行数:55,代码来源:Statistics.scala


示例2: Road

//设置package包名称以及导入依赖的类
package ui

import org.scalajs.dom.html.{Div, Element}
import org.scalajs.dom.{CanvasRenderingContext2D, document, html}
import ui.helper.HtmlCreator

object Road {
  val cellCountPerRow = 150
  val cellSizeInPixels = 5

  def setupUI(): Element = {

    val roadBox = HtmlCreator.create[Div]("simulation-box")

    val simulationCanvas = document.createElement("canvas")
    simulationCanvas.id = "simulation-canvas"
    simulationCanvas.setAttribute("width", cellCountPerRow * cellSizeInPixels + "px")

    roadBox.appendChild(simulationCanvas)

    roadBox
  }

  def draw(road: Vector[Option[Int]]): Unit = {
    val rows = road.length / cellCountPerRow
    val canvas = document.getElementById("simulation-canvas").asInstanceOf[html.Canvas]
    val ctx = canvas.getContext("2d").asInstanceOf[CanvasRenderingContext2D]
    canvas.width = cellCountPerRow * cellSizeInPixels
    canvas.height = rows * cellSizeInPixels
    ctx.strokeStyle = "red"
    ctx.lineWidth = 20

    road.zipWithIndex.foreach(r => {
      if (r._1.isDefined) {
        ctx.fillRect(cellSizeInPixels*(r._2 % cellCountPerRow), cellSizeInPixels*(r._2 / cellCountPerRow), cellSizeInPixels, cellSizeInPixels)
      }
      else {
        ctx.clearRect(cellSizeInPixels*(r._2 % cellCountPerRow), cellSizeInPixels*(r._2 / cellCountPerRow), cellSizeInPixels, cellSizeInPixels)
      }
    })

    ctx.stroke
  }
} 
开发者ID:tlewowski,项目名称:nagel-schreckenberg,代码行数:45,代码来源:Road.scala


示例3: ConfigurationBox

//设置package包名称以及导入依赖的类
package ui

import org.scalajs.dom.{Element, document}

object ConfigurationBox {
  def create(triggerCallback: SimulationTrigger => Unit): Element = {
    val configBox = document.createElement("form")
    configBox.id = "params-box"
    configBox.appendChild(WidthBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(DensityBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(ProbabilityBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(SpeedBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(SpeedStepBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(MinimumTimeoutBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(CountedIterationsBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(SimulationTriggeringButtons.setupUI(triggerCallback))

    configBox
  }
} 
开发者ID:tlewowski,项目名称:nagel-schreckenberg,代码行数:21,代码来源:ConfigurationBox.scala


示例4: Images

//设置package包名称以及导入依赖的类
package net.xylophones.frogger

import org.scalajs.dom.document

object Images {

  private val mediaPath = document.getElementById("frogger").getAttribute("mediaPath")
  
  private def fullPath(pth: String) = s"$mediaPath$pth"

  val tiles = new TiledImage(Image(fullPath("img/tiles.png")), 32, 32)
  val top = Image(fullPath("img/top.png"))
  val oneUp = Image(fullPath("img/1_up.png"))
  val highScore = Image(fullPath("img/high_score.png"))
  val nums = Image(fullPath("img/numbers.png"))
  val lifeImage = Image(fullPath("img/life.png"))
  val levelImage = Image(fullPath("img/level2.png"))
  val timeImage = Image(fullPath("img/time.png"))
  val frog = Image(fullPath("img/frog.png"))
  val deadFrog = Image(fullPath("img/deadfrog.png"))

} 
开发者ID:wjsrobertson,项目名称:scalajs-frogger,代码行数:23,代码来源:Images.scala


示例5: App

//设置package包名称以及导入依赖的类
package net.xylophones.frogger

import org.scalajs.dom
import org.scalajs.dom.document
import org.scalajs.dom.html.{Canvas}

import scala.scalajs.js.JSApp
import scala.scalajs.js.timers._

object App extends JSApp {
  private val canvas = document.getElementById("frogger").asInstanceOf[Canvas]
  val ctx = canvas.getContext("2d").asInstanceOf[dom.CanvasRenderingContext2D]
  private val mediaPath = canvas.getAttribute("mediaPath")
  private val soundPlayer = new SoundPlayer(mediaPath)

  def main(): Unit = {
    addCanvas()
    val m = Layers.initialModel()
    loop(model = m)
  }

  def loop(lastTime: Long = System.currentTimeMillis, model: Model): Unit = {
    draw(model)

    val interval: Long = System.currentTimeMillis() - lastTime
    val desiredPause = 1000 / 25
    val pause = Math.max(0, desiredPause - interval)

    setTimeout(pause) {
      val newModel: Model = updateModel(model)

      loop(System.currentTimeMillis(), newModel)
    }
  }

  private def updateModel(model: Model): Model = {
    val newModel = ModelUpdaters.updaters.foldLeft(model) {
      (updatedModel: Model, updater: ModelUpdater) => updater.updateIfApplicable(updatedModel)
    }

    for (s <- newModel.sounds) {soundPlayer.play(s)}

    newModel.copy(sounds = Seq())
  }

  def draw(model: Model) = {
    (model.layers.all zip model.positions).foreach { case (l, p) => l.draw(ctx, p, model) }

    model.layers.frogLayer.draw(ctx, model.frogPosition, model)
  }

  def addCanvas(): Unit = {
    canvas.width = Config.gameWidth
    canvas.height = Config.gameHeight
  }
} 
开发者ID:wjsrobertson,项目名称:scalajs-frogger,代码行数:57,代码来源:App.scala


示例6: Cookies

//设置package包名称以及导入依赖的类
package codes.mark.geilematte.facades

import org.scalajs.dom.document

import scala.scalajs.js.Date
import scalaz.std.list._

object Cookies {

  def read: Map[String, String] =
    document.cookie
      .split(";")
      .toList
      .map(_.split("=").toList)
      .flatMap(x =>
        (x.headOption, x.drop(1).headOption) match {
          case (Some(k), Some(v)) => List((k.trim, v))
          case _                  => Nil
        })
      .toMap

  def write(values:Map[String, String]): Unit = {
    val expiry = new Date(2020, 1)
    values.toList.foreach {
        case (k, v) =>
          val expires = expiry.toUTCString
          document.cookie = s"$k=$v;expires=$expires;path=/"
    }
  }
} 
开发者ID:i-am-the-slime,项目名称:geilematte,代码行数:31,代码来源:Cookies.scala


示例7: Context

//设置package包名称以及导入依赖的类
package org.codeape.sc.frontend

import io.udash._
import io.udash.wrappers.jquery._
import org.codeape.sc.shared.MainServerREST
import org.scalajs.dom
import org.scalajs.dom.{Element, document}

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scala.util.Try

object Context {
  implicit val executionContext = scalajs.concurrent.JSExecutionContext.Implicits.queue
  private val routingRegistry = new RoutingRegistryDef
  private val viewPresenterRegistry = new StatesToViewPresenterDef

  implicit val applicationInstance = new Application[RoutingState](routingRegistry, viewPresenterRegistry, RootState)

  import io.udash.rest._
  val port = Try(dom.window.location.port.toInt).getOrElse(80)
  val host = dom.window.location.hostname
  val restServer = DefaultServerREST[MainServerREST](host, port, "/api/")
}

object Init extends JSApp with StrictLogging {
  import Context._

  @JSExport
  override def main(): Unit = {
    logger.info("StampClock started")
    jQ(document).ready((_: Element) => {
      val appRoot = jQ("#application").get(0)
      if (appRoot.isEmpty) {
        logger.error("Application root element not found! Check your index.html file!")
      } else {
        applicationInstance.run(appRoot.get)
      }
    })
  }
} 
开发者ID:codeape,项目名称:StampClock,代码行数:42,代码来源:init.scala


示例8: ScalaJSExamples

//设置package包名称以及导入依赖的类
package com.outr.nextui.examples.browser

import com.outr.nextui.browser.ScalaJS
import com.outr.nextui.examples.Examples
import org.scalajs.dom.{Event, document, html}

import scala.scalajs.js.JSApp

object ScalaJSExamples extends JSApp {
  override def main(): Unit = {
    val div = document.createElement("div").asInstanceOf[html.Div]
    Examples().foreach { ui =>
      val a = document.createElement("a").asInstanceOf[html.Anchor]
      a.href = "#"
      a.addEventListener("click", {(evt: Event) =>
        document.body.removeChild(div)
        ScalaJS(ui)
      }, true)
      a.textContent = ui.name
      val p = document.createElement("p").asInstanceOf[html.Paragraph]
      p.appendChild(a)
      div.appendChild(p)
    }
    document.body.appendChild(div)
  }
} 
开发者ID:outr,项目名称:nextui,代码行数:27,代码来源:ScalaJSExamples.scala


示例9: Init

//设置package包名称以及导入依赖的类
package com.oni.udash

import acyclic.file

import io.udash._
import io.udash.wrappers.jquery._
import org.scalajs.dom.{ Element, document }

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scalacss.Defaults._
import scalacss.ScalatagsCss._
import scalatags.JsDom._
import com.oni.udash.styles._
import com.oni.udash.styles.OniStyles2
import com.oni.udash.styles.GlobalStyles
import com.oni.udash.styles.DemoStyles
import com.oni.udash.styles.partials.FooterStyles
import com.oni.udash.styles.partials.HeaderStyles
import org.scalajs.dom.raw.HTMLStyleElement

object Init extends JSApp with StrictLogging {
  import Context._

  @JSExport
  override def main(): Unit = {
    jQ(document).ready((_: Element) => {
      val appRoot = jQ("#application").get(0)
      if (appRoot.isEmpty) {
        logger.error("Application root element not found! Check your index.html file!")
      } else {
        applicationInstance.run(appRoot.get)

        jQ(GlobalStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(DemoStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(OniStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(OniStyles2.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(CsStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(CsStyles2.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(FooterStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(HeaderStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
      }
    })
  }
} 
开发者ID:ObjectNirvana,项目名称:oni-web,代码行数:46,代码来源:init.scala


示例10: TutorialApp

//设置package包名称以及导入依赖的类
package jp.ne.opt.client

import jp.ne.opt.domain.TodoStore

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import japgolly.scalajs.react.{ReactComponentB, ReactDOM}
import japgolly.scalajs.react.vdom.prefix_<^._
import org.scalajs.dom.document

object TutorialApp extends JSApp {
  def main(): Unit = {
    println("helloWorld")
  }

  @JSExport
  def count():Unit = {
    countNumber +=1
    println(countNumber)
  }
  var countNumber: Int = 1

  val Hello =
    ReactComponentB[String]("Hello")
      .render_P(name => <.div(^.id:="hoge","Hello there ", name))
      .build

  ReactDOM.render(Hello("hohohohoho"), document.getElementById("content"))
} 
开发者ID:opt-tech,项目名称:scalajs-react-todo,代码行数:30,代码来源:Main.scala


示例11: GoogleSearchBox

//设置package包名称以及导入依赖的类
package net.scalytica.blaargh.components

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import org.scalajs.dom.document


object GoogleSearchBox {

  class Backend($: BackendScope[Unit, Unit]) {

    def scriptGen() = {
      val cx = "007449460818485879211:oyngikjfvr0"
      val googleScript = {
        val scr = document.createElement("script")
        scr.setAttribute("type", "text/javascript")
        scr.setAttribute("async", "true")
        scr.setAttribute("src", s"${document.location.protocol}//cse.google.com/cse.js?cx=$cx")
        scr
      }

      val s = document.getElementsByTagName("script")(0)
      s.parentNode.insertBefore(googleScript, s)
    }

    def render() = {
      <.div(^.dangerouslySetInnerHtml("<gcse:search></gcse:search>"))
    }
  }

  val component = ReactComponentB[Unit]("GoogleSearchBox")
    .stateless
    .renderBackend[Backend]
    .componentWillMount($ => Callback($.backend.scriptGen()))
    .buildU


  def apply() = component()

} 
开发者ID:kpmeen,项目名称:blaargh,代码行数:41,代码来源:GoogleSearchBox.scala


示例12: SampleApp1

//设置package包名称以及导入依赖的类
package se.ta

import scala.concurrent.duration._
import scala.scalajs.js.JSApp

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable
import org.scalajs.dom.document

object SampleApp1 extends JSApp {

  def viewTick(tick: Long) =
    <.div(
      <.p(s"Tick: $tick seconds")
    )

  val Tick =
    ReactComponentB[Long]("Tick")
      .render_P(tick => viewTick(tick))
      .build

  def main(): Unit = {

    println("Starting counting  10 ticks")

    Observable.interval(1 second)
      .doOnNext(x => ReactDOM.render(Tick(x), document.body))
      .take(10)
      .dump("0")
      .subscribe()
  }
} 
开发者ID:ThomasAlexandre,项目名称:scalajs-elm,代码行数:35,代码来源:SampleApp1.scala


示例13: Main

//设置package包名称以及导入依赖的类
package helloBinding

import com.thoughtworks.binding.Binding.{Var, Vars}
import com.thoughtworks.binding.dom
import org.scalajs.dom.raw.Event
import org.scalajs.dom.html.Input
import org.scalajs.dom.document


object Main extends scalajs.js.JSApp {

  @dom
  def render = {
    val name = Var("Binding.scala")
    val show = Var(false)
    <div>
      <p>
        <input type="checkbox" id="showCheckbox" onchange={_: Event => show := showCheckbox.checked }/>
        <label for="showCheckbox">
          Say hello to <input id="nameInput" value={name.get} oninput={_: Event => name := nameInput.value}/>
        </label>
      </p>
      {
        if (show.bind) {
          <p>
            Hello, {name.bind}!
          </p>
        } else {
          <!-- Don't show hello. -->
        }
      }
    </div>
  }

  def main(): Unit = {
    dom.render(document.body, render)
  }
} 
开发者ID:ThoughtWorksInc,项目名称:Binding.scala-activator-template,代码行数:39,代码来源:Main.scala


示例14: Main

//设置package包名称以及导入依赖的类
package com.github.aafa.vending

import com.github.aafa.vending.diode._
import org.scalajs.dom.{Node, document}

import scala.scalajs.js.JSApp
import scalatags.JsDom.all._

object Main extends JSApp {
  AppCircuit.subscribe(AppCircuit.zoom(a => a))(_ => render())

  def main(): Unit = {
    render()
  }

  private def render() = {
    document.body.innerHTML = ""
    content(document.body)
  }

  def content(targetNode: Node): Unit = {
    val insertCoin = button(`class` := "insertCoin", onclick := { () => AppCircuit(InsertCoin(CandyCoin(1))) }, ">> Insert CandyCoin here <<")
    val candies = AppCircuit.zoom(_.listOfCandies).value
    val coinsSlot = AppCircuit.zoom(_.coinsSlot).value.value
    val getTheCandy = AppCircuit.zoom(_.getTheCandySlot).value.map(_.name)
    val info = AppCircuit.zoom(_.machineInfo).value

    targetNode.appendChild(
      div(`class` := "container",
        h2("Candies for everyone!"),
        div(info),
        div(insertCoin),
        div(coinsSlot + " coins"),
        ul(`class` := "candyList",
          candies map (c => div(
            button(`class` := "candy", onclick := { () => AppCircuit(PurchaseCandy(c.candy)) },
              s"Purchase ${c.candy.name} for ${c.price.value}cc, only ${c.quantity} left")))
        ),
        div(`class` := "footer",
          button(
            `class` := "get-candy-slot", onclick := { () => AppCircuit(CandyTakenFromSlot) },
            getTheCandy
          )
        )
      ).render
    )

  }
} 
开发者ID:aafa,项目名称:vending,代码行数:50,代码来源:Main.scala


示例15: DoiApp

//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi.gui

import scala.scalajs.js.JSApp
import org.scalajs.dom.document
import se.lu.nateko.cp.doi.gui.views.MainView

object DoiApp extends JSApp {

	val initState = DoiState(
		prefix = "10.5072",//test value; the actual one is fetched from backend
		dois = Nil,
		info = Map.empty,
		selected = None,
		ioState = IoState(None, None),
		alreadyExists = None,
		error = None
	)
	val store = new DoiRedux.Store(DoiReducer.reducer, initState)

	val mainView = new MainView(store)
	val renderer = new Renderer(mainView)
	store.subscribe(renderer)

	def main(): Unit = {
		val mainDiv = document.getElementById("main")
		mainDiv.parentNode.replaceChild(mainView.element.render, mainDiv)

		store.dispatch(ThunkActions.FetchDoiPrefix)
		store.dispatch(ThunkActions.DoiListRefreshRequest)
	}

} 
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:33,代码来源:DoiApp.scala


示例16: ErrorView

//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi.gui.views

import scalatags.JsDom.all._
import org.scalajs.dom.document
import se.lu.nateko.cp.doi.gui.DoiRedux
import se.lu.nateko.cp.doi.gui.ResetErrors

class ErrorView(widthPx: Int, heightPx: Int, d: DoiRedux.Dispatcher) {

	private[this] val errPadding = 15

	private[this] val errorList = div(
		width := widthPx - 2 * errPadding,
		color := Constants.formErrorsTextColor
	).render

	private val continue: () => Unit = () => d.dispatch(ResetErrors)

	private[this] val element = div(
		display := "none", position := "fixed",
		top := 0, bottom := 0,
		left := 0, right := 0,
		width := widthPx, height := heightPx,
		margin := "auto", padding := errPadding,
		zIndex := 10000,
		backgroundColor := Constants.errorInputBackground
	)(
		errorList,
		button(
			tpe := "button", cls := "btn btn-danger",
			onclick := continue,
			position := "absolute",
			right := errPadding, bottom := errPadding
		)("Continue")
	).render

	document.body.appendChild(element)

	def clearErrors(): Unit = {
		element.style.display = "none"
		errorList.innerHTML = ""
	}

	def appendError(msg: String): Unit = {

		val errorMessage = if(msg == null || msg.isEmpty) "Unknown error" else msg

		for(messageLine <- errorMessage.split("\n")){
			errorList.appendChild(
				p(messageLine).render
			)
		}

		element.style.display = "inline-block"
	}
} 
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:57,代码来源:ErrorView.scala


示例17: Context

//设置package包名称以及导入依赖的类
package io.udash.web.homepage

import io.udash._
import io.udash.wrappers.jquery._
import org.scalajs.dom.{Element, document}

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport

object Context {
  implicit val executionContext = scalajs.concurrent.JSExecutionContext.Implicits.queue
  private val routingRegistry = new RoutingRegistryDef
  private val viewPresenterRegistry = new StatesToViewPresenterDef

  implicit val applicationInstance = new Application[RoutingState](routingRegistry, viewPresenterRegistry, RootState)
}

object Init extends JSApp with StrictLogging {
  import Context._

  @JSExport
  override def main(): Unit = {
    jQ(document).ready((_: Element) => {
      val appRoot = jQ("#application").get(0)
      if (appRoot.isEmpty) {
        logger.error("Application root element not found! Check you index.html file!")
      } else applicationInstance.run(appRoot.get)
    })
  }
} 
开发者ID:UdashFramework,项目名称:udash-guide,代码行数:31,代码来源:init.scala


示例18: Template

//设置package包名称以及导入依赖的类
import org.scalajs.dom
import org.scalajs.dom.document
import org.scalajs.jquery.jQuery

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport

object Template extends JSApp {

  def appendPar(text:String) = {
    jQuery(document.body).append(s"<p>${text}</p>")
  }

  def setupUI() = {
    jQuery("<button type='button'>Click</button>")
      .appendTo(document.body)
      .click(() => appendPar("Template"))
  }

  @JSExport
  override def main(): Unit = {
    jQuery(setupUI _)
  }
} 
开发者ID:fbaumgardt,项目名称:scalajs-template,代码行数:25,代码来源:Template.scala


示例19: ExampleCallback

//设置package包名称以及导入依赖的类
package de.tu_berlin.formic.example

import de.tu_berlin.formic.client.NewInstanceCallback
import de.tu_berlin.formic.common.datastructure.client.{ClientDataStructureEvent, RemoteOperationEvent}
import de.tu_berlin.formic.common.datastructure.{DataStructureName, FormicDataStructure}
import de.tu_berlin.formic.datastructure.json.client.FormicJsonObject
import de.tu_berlin.formic.datastructure.linear.client.FormicString
import de.tu_berlin.formic.datastructure.tree.client.FormicIntegerTree
import org.scalajs.dom.document
import org.scalajs.jquery.jQuery


class ExampleCallback(val main: Main) extends NewInstanceCallback {

  override def newCallbackFor(instance: FormicDataStructure, dataType: DataStructureName): (ClientDataStructureEvent) => Unit = {
    instance match {
      case str: FormicString => main.updateUIForString(instance.dataStructureInstanceId)
      case tree: FormicIntegerTree => main.updateUIForTree(instance.dataStructureInstanceId)
      case json: FormicJsonObject => if(isBattleShip) main.newCallbackForBattleship(json) else main.updateUIForJson(instance.dataStructureInstanceId)
    }
  }

  override def doNewInstanceCreated(instance: FormicDataStructure, dataType: DataStructureName): Unit = {
    instance match {
      case str: FormicString =>
        main.strings += str
        val id = str.dataStructureInstanceId.id
        val inputId = id
        jQuery("body").append("<p>String data type with id " + id + "</p>")
        jQuery("body").append("<textarea rows=\"30\" cols=\"50\" class=\"stringInput\" id=\"" + inputId + "\"></textarea>")
        jQuery("#" + inputId).keypress(main.keyPressHandler(inputId))
        main.updateUIForString(str.dataStructureInstanceId)(RemoteOperationEvent(null))

      case tree: FormicIntegerTree =>
        main.trees += tree
        if (jQuery("body").has("#" + tree.dataStructureInstanceId.id).length == 0) {
          main.insertBasicTreeElements(tree.dataStructureInstanceId.id)
        }
        main.updateUIForTree(tree.dataStructureInstanceId)(null)

      case json: FormicJsonObject =>
        main.jsons += json
        if (isBattleShip) {
          //in order to force Battleship to update the UI we invoke the callback here manually
          json.callback(null)
        } else {
          if (jQuery("body").has("#" + json.dataStructureInstanceId.id).length == 0) {
            main.insertJsonManipulationElements(json.dataStructureInstanceId.id)
          }
          main.updateUIForJson(json.dataStructureInstanceId)(null)
        }
    }
  }

  def isBattleShip = document.location.href.contains("battleship")
} 
开发者ID:rbraeunlich,项目名称:formic,代码行数:57,代码来源:ExampleCallback.scala


示例20: Main

//设置package包名称以及导入依赖的类
package benchmark

import org.scalajs.dom.document

import scala.scalajs.js
import scala.scalajs.js.|

object Main extends js.JSApp {

  def sequence[A](eventuallyAs: Seq[js.Thenable[A]]): js.Thenable[Seq[A]] =
    eventuallyAs.foldRight[js.Thenable[List[A]]](js.Promise.resolve[List[A]](List.empty[A])) { (eventuallyA, eventuallyAs) =>
      eventuallyA.`then`[List[A]](
        (a: A) => {
          eventuallyAs.`then`[List[A]](
            (as: List[A]) => (a :: as): (List[A] | js.Thenable[List[A]]),
            js.undefined
          ): (List[A] | js.Thenable[List[A]])
        },
        js.undefined
      )
    }

  def sequenceBenchmark(): js.Thenable[_] = {
    sequence((1 to 50000).map((i: Int) => js.Promise.resolve[Int](i)))
  }

  def main() = {
    val startTime = (new js.Date).getTime()
    sequenceBenchmark().`then`[Unit](_ => {
      val endTime = (new js.Date).getTime()
      document.getElementById("result").textContent = (endTime - startTime).toString
    }, js.undefined)
    ()
  }

} 
开发者ID:julienrf,项目名称:faithful,代码行数:37,代码来源:Main.scala



注:本文中的org.scalajs.dom.document类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ReceiveTimeout类代码示例发布时间:2022-05-23
下一篇:
Scala StandardScalerModel类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap