本文整理汇总了Scala中scala.scalajs.js类的典型用法代码示例。如果您正苦于以下问题:Scala js类的具体用法?Scala js怎么用?Scala js使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了js类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: DocumentTest
//设置package包名称以及导入依赖的类
package ch.epfl.callgraph.visualization
import ch.epfl.callgraph.utils.Utils.CallGraph
import ch.epfl.callgraph.visualization.view.{D3GraphView, HtmlView}
import org.junit.Assert._
import org.junit.{Before, Test}
import org.scalajs.dom.html._
import org.scalajs.{dom => sdom}
import upickle.{default => upickle}
import scala.scalajs
import scala.scalajs.js
import scala.scalajs.js.Dynamic.global
class DocumentTest {
val $ = global.jQuery
@Before
def setupDocument() : Unit = {
$("body").html("")
$("body")
.append(
global.jQuery("<div id=\"header\"><h1>Scala.js Call Graph Visualization</h1></div>" +
"<div id=\"nav\" style=\"overflow:auto\"></div>" +
"<div id=\"main\" style=\"overflow:auto\"></div>"))
HtmlView.main() // setup the file upload button
D3GraphView.setCallGraph(upickle.read[CallGraph](generateGraph))
HtmlView.updateHtmlAfterLoad(sdom.document.getElementById("nav").asInstanceOf[Div])
D3GraphView.renderGraph()
}
def generateGraph = {
"""{"classes":[{"encodedName":"s_Predef$Triple$2","displayName":"scala.Predef$Triple$2","isExported":true,"superClass":[],"interfaces":[],"methods":[]}]}"""
}
@Test def testInitialDOM(): Unit = {
assertEquals(1, $("#header").length)
assertEquals(1, $("#nav").length)
assertEquals(1, $("#main").length)
}
@Test def testInitialLayer : Unit = {
HtmlView.showLayers
assertEquals(1, $("li > a.active").length)
}
@Test def testSvgSingleNode : Unit = {
println($("svg").html())
$("svg").find("circle").each({(li: Html) => {
println($(li).attr("class"))
// $(li).contextmenu()
}}: scalajs.js.ThisFunction)
assertEquals(1, $("svg").find("circle").length)
}
}
开发者ID:lionelfleury,项目名称:scala-js-call-graph,代码行数:60,代码来源:DocumentTest.scala
示例2: UserAgentService
//设置package包名称以及导入依赖的类
package org.danielnixon.progressive.services
import org.danielnixon.progressive.shared.Wart
import org.scalajs.dom.Window
import org.danielnixon.saferdom.implicits._
import scala.scalajs.js
class UserAgentService(window: Window) {
val isTouchDevice: Boolean = window.document.documentElementOpt.exists(d => isDefined(d, "ontouchstart"))
val meetsRequirements: Boolean = {
isDefined(window, "WeakMap") &&
isDefined(window, "history") &&
isDefined(window.history, "pushState") &&
isDefined(window.document, "querySelector") &&
window.document.bodyOpt.exists(b => isDefined(b, "matches")) &&
window.document.bodyOpt.exists(b => isDefined(b, "closest"))
}
@SuppressWarnings(Array(Wart.AsInstanceOf))
private def isDefined(obj: js.Object, prop: String): Boolean = {
!js.isUndefined(obj.asInstanceOf[js.Dynamic].selectDynamic(prop))
}
}
开发者ID:danielnixon,项目名称:progressive,代码行数:28,代码来源:UserAgentService.scala
示例3: VariantBrowser
//设置package包名称以及导入依赖的类
package variantBrowser
import org.scalajs.dom
import variantBrowser.components.VariantBrowserClient
import scala.scalajs.js
import scala.scalajs.js.annotation.JSExport
import japgolly.scalajs.react.extra.router.StaticDsl.Route
import japgolly.scalajs.react.{Callback, ReactDOM}
import japgolly.scalajs.react.extra.router._
@JSExport
object VariantBrowser extends js.JSApp{
val baseUrl = BaseUrl("http://bioinfo01-ingemm.salud.madrid.org:9000")
// Define the locations (pages) used in this application
sealed trait Loc
case class Home() extends Loc
val routerConfig = RouterConfigDsl[Loc].buildConfig { dsl =>
import dsl._
( emptyRule
| dynamicRouteCT( ("/").caseClass[Home] ) ~> dynRenderR( (page,ctl) => VariantBrowserClient(ctl, page))
).notFound(redirectToPath(root)(Redirect.Replace))
}
@JSExport
def main() : Unit = {
dom.console.info(s"Initializing scalajs VariantBrowser lab")
val router = Router( baseUrl, routerConfig.logToConsole)
ReactDOM.render( router(), dom.document.getElementById("wrapper"))
}
}
开发者ID:ichbink,项目名称:goyoVariantBrowser,代码行数:35,代码来源:VariantBrowser.scala
示例4: identify
//设置package包名称以及导入依赖的类
package slate
import monix.eval.Task
import monix.execution.Cancelable
import slate.chrome._
import scala.scalajs.js
import scala.scalajs.js.UndefOr
object identify {
def chromeCallbackToTask[T](callbackTaker: (T => Unit) => Unit): Task[T] = {
Task.create[T] { (_, callback) =>
callbackTaker { result =>
ChromeRuntime.lastError.fold(callback.onSuccess(result)) { ex =>
callback.onError(ChromeErrorException(ex.message))
}
}
Cancelable.empty
}
}
def getAuthToken(interactive: Boolean = false, accountInfo: UndefOr[String] = js.undefined, scopes: UndefOr[js.Array[String]] = js.undefined): Task[String] =
chromeCallbackToTask(ChromeIdentity.fetchAuthToken(new GetAuthTokenOptions(interactive, accountInfo.map(new AccountInfo(_)), scopes), _))
def launchWebAuthFlow(interactive: Boolean = false, url: String): Task[String] =
chromeCallbackToTask(ChromeIdentity.launchWebAuthFlow(new LaunchWebAuthFlowOptions(url, interactive), _))
def removeCachedAuthToken(token: String): Task[Unit] =
chromeCallbackToTask(ChromeIdentity.removeCachedAuthToken(new RemoveCachedAuthTokenOptions(token), _))
case class ChromeErrorException(message: UndefOr[String]) extends Exception(message.getOrElse("No error message"))
}
开发者ID:edmundnoble,项目名称:slate,代码行数:35,代码来源:identify.scala
示例5: DatedAppContent
//设置package包名称以及导入依赖的类
package slate
package models
import upickle.Js
import scala.scalajs.js
case class DatedAppContent(content: List[ExpandableContentModel], date: js.Date)
object DatedAppContent {
implicit val pkl: upickle.default.Reader[DatedAppContent] with upickle.default.Writer[DatedAppContent] =
new upickle.default.Reader[DatedAppContent] with upickle.default.Writer[DatedAppContent] {
override def read0: PartialFunction[Js.Value, DatedAppContent] = Function.unlift[Js.Value, DatedAppContent] {
case Js.Obj([email protected]_*) =>
for {
content <- values.find(_._1 == "content").flatMap(t => ExpandableContentModel.pkls.read.lift(t._2))
date <- values.find(_._1 == "date").flatMap {
case (_, Js.Num(n)) => Some(new js.Date(n))
case _ => None
}
} yield DatedAppContent(content, date)
case _ => None
}
override def write0: DatedAppContent => Js.Value = { m =>
Js.Obj("date" -> Js.Num(m.date.getTime()), "content" -> ExpandableContentModel.pkls.write(m.content))
}
}
}
开发者ID:edmundnoble,项目名称:slate,代码行数:32,代码来源:DatedAppContent.scala
示例6: LZString
//设置package包名称以及导入依赖的类
package slate.bindings
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
import scala.scalajs.js.typedarray.Uint8Array
@js.native
@JSName("LZString")
object LZString extends js.Any {
@js.native
def compressToUint8Array(str: String): Uint8Array = js.native
@js.native
def decompressFromUint8Array(buf: Uint8Array): String = js.native
@js.native
def compressToUTF16(str: String): String = js.native
@js.native
def decompressFromUTF16(str: String): String = js.native
@js.native
def compress(str: String): String = js.native
@js.native
def decompress(str: String): String = js.native
}
开发者ID:edmundnoble,项目名称:slate,代码行数:28,代码来源:LZString.scala
示例7: Application
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client
import com.momentjs.Moment
import com.thoughtworks.binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom
import org.scalajs.dom.raw._
import scala.scalajs.js
import scala.scalajs.js.annotation._
import walfie.gbf.raidfinder.client.util.time._
import walfie.gbf.raidfinder.client.ViewModel.TimeFormat
import walfie.gbf.raidfinder.protocol._
@JSExport("GbfRaidFinder")
object Application {
@JSExport
def init(url: String): Unit = {
val maxReconnectInterval = Duration.seconds(10)
val websocket = new BinaryProtobufWebSocketClient(url, maxReconnectInterval)
val client: RaidFinderClient = new WebSocketRaidFinderClient(
websocket, dom.window.localStorage, SystemClock
)
Moment.defineLocale("en-short", MomentShortLocale)
val notification = new views.SnackbarNotification
val viewState = ViewModel.loadState()
// Update currentTime every 30 seconds
val currentTime: Var[Double] = Var(js.Date.now())
js.timers.setInterval(Duration.seconds(30).milliseconds) {
client.truncateColumns(50)
currentTime := js.Date.now()
}
val div = dom.document.createElement("div")
div.classList.add("gbfrf-container")
val mainContent = views.MainContent.mainContent(
client, ViewModel.loadState(), notification, currentTime, client.isConnected
)
binding.dom.render(div, mainContent)
dom.document.body.appendChild(div)
}
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:49,代码来源:Application.scala
示例8: now
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client.util
import java.util.Date
import scala.scalajs.js
package time {
trait Clock { def now(): Date }
object SystemClock extends Clock { def now(): Date = new Date() }
case class Duration(milliseconds: Long) extends AnyVal
object Duration {
def seconds(s: Long): Duration = Duration(s * 1000)
def minutes(m: Long): Duration = Duration(m * 60 * 1000)
def hours(h: Long): Duration = Duration(h * 3600 * 1000)
def days(d: Long): Duration = Duration(d * 24 * 3600 * 1000)
}
}
package object time {
val MomentShortLocale: js.Dictionary[js.Any] = js.Dictionary(
"parentLocale" -> "en",
"relativeTime" -> js.Dictionary(
"future" -> "in %s",
"past" -> "%s ago",
"s" -> "now",
"ss" -> "%ss",
"m" -> "1m",
"mm" -> "%dm",
"h" -> "1h",
"hh" -> "%dh",
"d" -> "1d",
"dd" -> "%dd",
"M" -> "1M",
"MM" -> "%dM",
"y" -> "1Y",
"yy" -> "%dY"
)
)
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:40,代码来源:time.scala
示例9: NotificationSound
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client
import org.scalajs.dom.raw.HTMLAudioElement
import scala.scalajs.js
package audio {
case class NotificationSound(id: NotificationSoundId, fileName: String) {
def play(): Unit = {
NotificationSounds.audioCache.getOrElseUpdate(fileName, {
js.Dynamic
.newInstance(js.Dynamic.global.Audio)(pathPrefix + fileName)
.asInstanceOf[HTMLAudioElement]
}).play()
}
}
}
package object audio {
type NotificationSoundId = Int
private[audio] val pathPrefix = "audio/"
object NotificationSounds {
// When adding new items, don't change the numeric IDs
val all: Seq[NotificationSound] = Seq(
1 -> "oh-finally.ogg",
2 -> "oringz-w425.ogg",
3 -> "pedantic.ogg",
4 -> "suppressed.ogg",
5 -> "system.ogg",
6 -> "tweet.ogg",
7 -> "you-wouldnt-believe.ogg",
8 -> "youve-been-informed.ogg"
).map { case (id, fileName) => NotificationSound(id, fileName) }.sortBy(_.fileName)
val findById: NotificationSoundId => Option[NotificationSound] =
all.map(n => n.id -> n).toMap.get _
private[audio] var audioCache: js.Dictionary[HTMLAudioElement] = js.Dictionary()
}
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:43,代码来源:Audio.scala
示例10: binding
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client.views
import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom.raw._
import scala.scalajs.js
import walfie.gbf.raidfinder.client.syntax.HTMLElementOps
trait Notification {
def binding: Binding[Element]
def enqueue(message: String): Unit
}
class SnackbarNotification extends Notification {
@binding.dom
val binding: Binding[Element] = {
<div class="mdl-js-snackbar mdl-snackbar">
<div class="mdl-snackbar__text"></div>
<button class="mdl-snackbar__action" type="button"></button>
</div>
}.mdl
def enqueue(message: String): Unit = {
val data = js.Dictionary("message" -> message, "timeout" -> "1000")
Binding {
binding.bind.asInstanceOf[js.Dynamic].MaterialSnackbar.showSnackbar(data)
}
}
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:31,代码来源:Notification.scala
示例11: HTMLElementOps
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client
import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom
import org.scalajs.dom.raw._
import scala.collection.mutable.Buffer
import scala.scalajs.js
import walfie.gbf.raidfinder.client.ViewModel.ImageQuality
import walfie.gbf.raidfinder.protocol._
import js.Dynamic.global
package object syntax {
implicit class HTMLElementOps[T <: HTMLElement](val elem: T) extends AnyVal {
def :=(elements: TraversableOnce[T]): Buffer[T] = {
buffer.clear()
buffer ++= elements
}
}
implicit class StringOps(val string: String) extends AnyVal {
def addIf(condition: Boolean, s: String): String =
if (condition) s"$string $s" else string
}
implicit class LanguageOps(val language: Language) extends AnyVal {
def shortName: Option[String] = language match {
case Language.JAPANESE => Some("JP")
case Language.ENGLISH => Some("EN")
case _ => None
}
}
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:37,代码来源:package.scala
示例12: Moment
//设置package包名称以及导入依赖的类
package com.momentjs
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
@js.native
@JSName("moment")
object Moment extends js.Object {
def apply(millis: Double): Date = js.native
def locale(localeName: String): Unit = js.native
def defineLocale(localeName: String, settings: js.Dictionary[js.Any]): Unit = js.native
}
@js.native
trait Date extends js.Object {
def fromNow(): String = js.native
def fromNow(withoutSuffix: Boolean): String = js.native
def from(millis: Double, withoutSuffix: Boolean): String = js.native
def format(stringFormat: String): String = js.native
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:22,代码来源:package.scala
示例13: HttpConfig
//设置package包名称以及导入依赖的类
package io.scalajs.npm.angularjs.http
import scala.scalajs.js
import scala.scalajs.js.annotation.ScalaJSDefined
import scala.scalajs.js.|
@ScalaJSDefined
class HttpConfig(var method: js.UndefOr[String] = js.undefined,
var url: js.UndefOr[String] = js.undefined,
var params: js.UndefOr[js.Dictionary[js.Any]] = js.undefined,
var data: js.Any = js.undefined,
var headers: js.UndefOr[js.Dictionary[js.Any]] = js.undefined,
var xsrfHeaderName: js.UndefOr[String] = js.undefined,
var xsrfCookieName: js.UndefOr[String] = js.undefined,
var transformResponse: js.UndefOr[js.Array[js.Function]] = js.undefined,
// js.Function2[js.Any = js.undefined, js.Any, js.Any]
var transformRequest: js.UndefOr[js.Array[js.Function]] = js.undefined,
// js.Function2[js.Any, js.Any, js.Any]
var cache: js.Any = js.undefined,
var withCredentials: js.UndefOr[Boolean] = js.undefined,
var timeout: js.UndefOr[Int | Double] = js.undefined,
var responseType: js.UndefOr[String] = js.undefined)
extends js.Object
开发者ID:scalajs-io,项目名称:angular,代码行数:25,代码来源:HttpConfig.scala
示例14: KaTex
//设置package包名称以及导入依赖的类
package codes.mark.geilematte.facades
import org.scalajs.dom
import scala.scalajs.js
import scala.scalajs.js.JavaScriptException
import scala.scalajs.js.annotation.JSName
@JSName("katex")
@js.native
object KaTex extends js.Object {
def render(latex: String, target: dom.Element, config:js.Object = new KaTexConfig(true)): Unit = js.native
}
@js.native
class KaTexConfig(var displayMode:Boolean) extends js.Object
object SafeKaTex {
def render(latex: String, target: dom.Element): Option[String] =
try {
KaTex.render(latex, target)
Option.empty
} catch {
case (e: JavaScriptException) =>
Option(e.getMessage)
}
}
开发者ID:i-am-the-slime,项目名称:geilematte,代码行数:28,代码来源:KaTex.scala
示例15: Client
//设置package包名称以及导入依赖的类
package kartograffel.client
import eu.timepit.refined.api.RefType
import io.circe.syntax._
import kartograffel.shared.model.Position
import kartograffel.shared.model.Position.{Latitude, Longitude}
import org.scalajs.dom
import org.scalajs.dom.{window, Coordinates, PositionError, PositionOptions}
import org.scalajs.jquery.jQuery
import scala.scalajs.js
object Client {
def main(args: Array[String]): Unit = {
jQuery("body").append("<p>Hallo!</p>")
val opts = js.Object().asInstanceOf[PositionOptions]
opts.timeout = 50000
opts.enableHighAccuracy = true
window.navigator.geolocation.getCurrentPosition(
{ pos: dom.Position =>
val loc = locationFrom(pos.coords).get
println("Location" + locationFrom(pos.coords))
println(pos)
jQuery.post(url = "/api/post",
data = loc.asJson.spaces2,
success = null,
dataType = null)
}, { err: PositionError =>
println(err.code)
println(err.message)
},
opts
)
println("Hello, world!1111")
}
def locationFrom(coordinates: Coordinates): Option[Position] = {
val location = for {
latitude <- RefType.applyRef[Latitude](coordinates.latitude)
longitude <- RefType.applyRef[Longitude](coordinates.longitude)
} yield Position(latitude, longitude)
location.toOption
}
}
开发者ID:fthomas,项目名称:kartograffel,代码行数:50,代码来源:Client.scala
示例16: JSMap
//设置package包名称以及导入依赖的类
package akka.util
import scala.collection.mutable.{ Map, MapLike }
import scala.scalajs.js
import js.annotation.JSBracketAccess
final class JSMap[A] private () extends Map[String, A]
with MapLike[String, A, JSMap[A]] {
private[this] val dict: js.Dictionary[A] = js.Dictionary.empty[A]
override def empty: JSMap[A] = new JSMap[A]
override def get(key: String): Option[A] = {
if (dict.isDefinedAt(key)) Some(dict(key))
else None
}
override def +=(kv: (String, A)): this.type = {
dict(kv._1) = kv._2
this
}
override def -=(key: String): this.type = {
dict.delete(key)
this
}
override def iterator: Iterator[(String, A)] = {
for {
key <- dict.keys.iterator
} yield {
(key, dict(key))
}
}
}
object JSMap {
def empty[A]: JSMap[A] = new JSMap[A]
}
开发者ID:Starofall,项目名称:Chakka,代码行数:42,代码来源:JSMap.scala
示例17: ConsumerOptions
//设置package包名称以及导入依赖的类
package io.scalajs.npm.kafkanode
import scala.scalajs.js
import scala.scalajs.js.annotation.ScalaJSDefined
@ScalaJSDefined
class ConsumerOptions(var groupId: js.UndefOr[String] = js.undefined,
var autoCommit: js.UndefOr[Boolean] = js.undefined,
var autoCommitIntervalMs: js.UndefOr[Int] = js.undefined,
var fetchMaxWaitMs: js.UndefOr[Int] = js.undefined,
var fetchMinBytes: js.UndefOr[Int] = js.undefined,
var fetchMaxBytes: js.UndefOr[Int] = js.undefined,
var fromOffset: js.UndefOr[Long] = js.undefined,
var encoding: js.UndefOr[String] = js.undefined)
extends js.Object
开发者ID:scalajs-io,项目名称:kafka-node,代码行数:17,代码来源:ConsumerOptions.scala
示例18: OffsetTest
//设置package包名称以及导入依赖的类
package io.scalajs.npm.kafkanode
import io.scalajs.JSON
import io.scalajs.nodejs.process
import org.scalatest.FunSpec
import scala.scalajs.js
class OffsetTest extends FunSpec {
describe("Offset") {
it("can fetch data") {
process.env.get("ZK_HOST") match {
case None =>
info("No Zookeeper host was specified. Set 'ZK_HOST=localhost:2181'")
case Some(zkConnect) =>
val client = new Client(zkConnect)
val offset = new Offset(client)
val payloads = js.Array(new FetchRequest(topic = "t", partition = 0))
offset.fetch[js.Any](payloads, (err, data) => {
info(s"data: ${JSON.stringify(data)}")
client.close()
})
}
}
}
}
开发者ID:scalajs-io,项目名称:kafka-node,代码行数:33,代码来源:OffsetTest.scala
示例19: ConsumerGroupTest
//设置package包名称以及导入依赖的类
package io.scalajs.npm.kafkanode
import io.scalajs.nodejs.process
import org.scalatest.FunSpec
import scala.scalajs.js
class ConsumerGroupTest extends FunSpec {
describe("ConsumerGroup") {
it("should be created like ConsumerGroup(options, ['RebalanceTopic', 'RebalanceTest'])") {
process.env.get("ZK_HOST") match {
case None =>
info("No Zookeeper host was specified. Set 'ZK_HOST=localhost:2181'")
case Some(zkConnect) =>
new ConsumerGroup(options = createOptions(zkConnect), topics = js.Array("RebalanceTopic", "RebalanceTest"))
}
}
it("should be created like ConsumerGroup(options, 'RebalanceTopic')") {
process.env.get("ZK_HOST") match {
case None =>
info("No Zookeeper host was specified. Set 'ZK_HOST=localhost:2181'")
case Some(zkConnect) =>
new ConsumerGroup(createOptions(zkConnect), "RebalanceTopic")
}
}
}
private def createOptions(zkConnect: String) = {
new ConsumerGroupOptions(
host = zkConnect,
zk = js.undefined, // put client zk settings if you need them (see Client)
batch = js.undefined, // put client batch settings if you need them (see Client)
ssl = true, // optional (defaults to false) or tls options hash
groupId = "ExampleTestGroup",
sessionTimeout = 15000,
// An array of partition assignment protocols ordered by preference.
// "roundrobin" or "range" string for built ins (see below to pass in custom assignment protocol)
protocol = js.Array("roundrobin"),
// Offsets to use for new groups other options could be "earliest" or "none" (none will emit an error if no offsets were saved)
// equivalent to Java client"s auto.offset.reset
fromOffset = "latest", // default
// how to recover from OutOfRangeOffset error (where save offset is past server retention) accepts same value as fromOffset
outOfRangeOffset = "earliest", // default
migrateHLC = false, // for details please see Migration section below
migrateRolling = true
)
}
}
开发者ID:scalajs-io,项目名称:kafka-node,代码行数:58,代码来源:ConsumerGroupTest.scala
示例20: ClientTest
//设置package包名称以及导入依赖的类
package io.scalajs.npm.kafkanode
import io.scalajs.nodejs.{console, process}
import io.scalajs.util.PromiseHelper.Implicits._
import org.scalatest.FunSpec
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
class ClientTest extends FunSpec {
private val topic = "testing"
describe("Client") {
it("should produce and consume data") {
process.env.get("ZK_HOST") match {
case None =>
info("No Zookeeper host was specified. Set 'ZK_HOST=localhost:2181'")
case Some(zkConnect) =>
val client = new Client(zkConnect)
val producer = new Producer(client)
producer.createTopicsFuture(topics = js.Array(topic), async = true) foreach { _ =>
console.log(s"Created topic $topic")
}
val consumer = new Consumer(
client,
js.Array(new FetchRequest(topic = topic, offset = 0)),
new ConsumerOptions(
groupId = "kafka-node-group",
autoCommit = true,
autoCommitIntervalMs = 5000,
fetchMaxWaitMs = 100,
fetchMinBytes = 4,
fetchMaxBytes = 1024 * 1024,
fromOffset = 0L,
encoding = "utf8"
)
)
consumer.onMessage((message: String) => {
console.log("message: %j", message)
})
consumer.onError { error =>
console.log("error: %j", error)
}
}
}
}
}
开发者ID:scalajs-io,项目名称:kafka-node,代码行数:57,代码来源:ClientTest.scala
注:本文中的scala.scalajs.js类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论