当前位置: 首页>>代码示例>>Scala>>正文


Scala window类代码示例

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


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

示例1: views

//设置package包名称以及导入依赖的类
package org.danielnixon.progressive

import org.scalajs.dom.window
import org.danielnixon.progressive.services._

trait Components {
  this: EventHandlers =>

  def views: Views

  def elements: KeyElements

  lazy val userAgentService: UserAgentService = new UserAgentService(window)

  lazy val historyService = new HistoryService(window)

  lazy val formSerializer = new FormSerializer

  lazy val eventService: EventService = new EventService

  lazy val focusManagementService: FocusManagementService =
    new FocusManagementService(window, scrollOffset _, userAgentService)

  lazy val ajaxService: AjaxService = new AjaxService

  lazy val targetService: TargetService = new TargetService

  lazy val refreshService: RefreshService =
    new RefreshService(Global.virtualDom, Global.vdomParser, eventHandlerSetupService, ajaxService, applyDiff)

  lazy val hijaxService: HijaxService = {
    new HijaxService(
      window,
      new QueryStringService(formSerializer),
      historyService,
      userAgentService,
      new TransitionsService(
        window,
        elements.announcementsElement,
        elements.errorElement,
        new AnimationService,
        views,
        new VDomService(Global.virtualDom, Global.vdomParser)
      ),
      focusManagementService,
      refreshService,
      new EnableDisableService,
      ajaxService,
      eventHandlerSetupService,
      formSerializer,
      eventService,
      targetService,
      preFormSubmit,
      postFormSubmit
    )
  }

  lazy val eventHandlerSetupService: EventHandlerSetupService =
    new EventHandlerSetupService(refreshService, hijaxService, additionalSetupInitial, additionalSetup)
} 
开发者ID:danielnixon,项目名称:progressive,代码行数:61,代码来源:Components.scala

示例2: initialize

//设置package包名称以及导入依赖的类
package org.danielnixon.progressive

import org.scalajs.dom.window

import org.danielnixon.progressive.shared.Wart

import scala.collection.immutable.Seq
import scala.scalajs.js


  def initialize(components: Components): Unit = {
    if (components.userAgentService.meetsRequirements && dependenciesExist) {
      components.historyService.initializeHistory()
      window.onpopstate = components.historyService.onPopState _
      components.eventHandlerSetupService.setupInitial(components.elements.body)
    }
  }

  @SuppressWarnings(Array(Wart.Any))
  private val dependenciesExist: Boolean = !Seq(Global.virtualDom, Global.vdomParser).exists(js.isUndefined)
} 
开发者ID:danielnixon,项目名称:progressive,代码行数:22,代码来源:Progressive.scala

示例3: 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

示例4: Omis

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

import com.omis.User
import com.omis.client.handlers.LoginUser
import com.omis.client.router.ApplicationRouter
import com.omis.client.services.{CoreApi, OmisCircuit}
import org.scalajs.dom
import play.api.libs.json.Json
import diode.AnyAction._
import org.scalajs.dom.window

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js

object Omis extends js.JSApp {

  def main(): Unit = {
    //    require()
    println("Application started")
    CoreApi.authenticate.map { e =>
      val user = Json.parse(e).validate[User].get
      OmisCircuit.dispatch(LoginUser(user))
      dom.window.location.href = "/#/dashboard"
      //            window.location.replace("")
    }.recover {
      case _ => println("user not logged in")
    }

    ApplicationRouter.router().renderIntoDOM(dom.document.getElementById("root"))
  }
} 
开发者ID:iriddhi,项目名称:mis,代码行数:32,代码来源:Omis.scala

示例5: LoginUser

//设置package包名称以及导入依赖的类
package com.omis.client.handlers

import com.omis.User
import com.omis.client.RootModels.UserRootModel
import com.omis.client.services.CoreApi
import diode.{ActionHandler, ActionResult, ModelRW}
import org.scalajs.dom.window

case class LoginUser(user: User)

case class LogoutUser()

class UserHandler[M](modelRW: ModelRW[M, UserRootModel]) extends ActionHandler(modelRW) {
  override def handle: PartialFunction[Any, ActionResult[M]] = {
    case LoginUser(user) =>
      updated(value.copy(user = user, isLoggedIn = true))

    case LogoutUser() =>
      // todo: Cancel all subscribe request for all sessions
      window.localStorage.clear()
      CoreApi.logout()
      updated(value.copy(isLoggedIn = false))

  }
} 
开发者ID:iriddhi,项目名称:mis,代码行数:26,代码来源:UserHandler.scala

示例6: CoreApi

//设置package包名称以及导入依赖的类
package com.omis.client.services

import com.omis.{EmpDetails, UserReg}
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.window
import play.api.libs.json.Json

import scala.concurrent.Future
import org.scalajs.dom.window

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue


object CoreApi {

  private def ajaxPost(requestContent: String, apiUrl: String): Future[String] = {
    Ajax.post(
      url = apiUrl,
      data = requestContent,
      headers = Map("Content-Type" -> "application/json;charset=UTF-8", "X-Auth-Token" -> window.localStorage.getItem("X-Auth-Token"))
    ).map(_.responseText)
  }

  private def ajaxGet(url: String): Future[String] = {
    Ajax.get(
      url = s"/${url}",
      headers = Map("X-Auth-Token" -> window.localStorage.getItem("X-Auth-Token"))
    ).map(_.responseText)
  }

  def login(userReg: UserReg) = {
    ajaxPost(Json.stringify(Json.toJson[UserReg](userReg)), "login")
  }

  def signUp(userReg: UserReg) = {
    ajaxPost(Json.stringify(Json.toJson[UserReg](userReg)), "signup")
  }

  def addEmployee(empDetails: EmpDetails) = {
    ajaxPost(Json.stringify(Json.toJson[EmpDetails](empDetails)), "createemp")
  }

  def logout() = ajaxGet("logout")

  def getAllEmp = ajaxGet("allemp")

  def getEmp = ajaxGet("emp")

  val authenticate = ajaxGet("authenticate")
} 
开发者ID:iriddhi,项目名称:mis,代码行数:51,代码来源:CoreApi.scala

示例7: BootstrapTestApp

//设置package包名称以及导入依赖的类
package com.karasiq.bootstrap.test.frontend

import com.karasiq.bootstrap.Bootstrap.default._
import org.scalajs.dom
import org.scalajs.dom.window
import org.scalajs.jquery._
import rx._

import scala.language.postfixOps
import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scalaTags.all._

@JSExport
object BootstrapTestApp extends JSApp {
  @JSExport
  override def main(): Unit = {
    jQuery(() ? {
      // Table tab will appear after 3 seconds
      val tableVisible = Var(false)
      val tabTitle = Var("Wait...")

      // Show table tab in 3 seconds
      window.setTimeout(() ? {
        tableVisible.update(true)
        window.setTimeout(() => { tabTitle() = "Table" }, 1000)
      }, 3000)
      
      val tabs = Var(Seq[NavigationTab](
        NavigationTab(tabTitle, "table", "table".faFwIcon, TestTable(), tableVisible.reactiveShow),
        NavigationTab("Carousel", "carousel", "picture".glyphicon, TestCarousel("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Big_Wood%2C_N2.JPG/1280px-Big_Wood%2C_N2.JPG")),
        NavigationTab("ToDo list", "todo", "fort-awesome".faFwIcon, TodoList()),
        NavigationTab("Text rendering", "text", "envelope".glyphicon, Bootstrap.jumbotron(
          FormInput.textArea(a("Text rendering", href := "serverside.html"), rows := 30, readonly, TestHtmlPage())
        ))
      ))

      val navigationBar = NavigationBar()
        .withBrand("Scala.js Bootstrap Test", href := "https://github.com/Karasiq/scalajs-bootstrap")
        .withTabs(tabs)
        .withContentContainer(content ? GridSystem.container(id := "main-container", GridSystem.mkRow(content)))
        .withStyles(NavigationBarStyle.inverse, NavigationBarStyle.fixedTop)
        .build()

      // Render page
      navigationBar.applyTo(dom.document.body)

      // Reactive navbar test
      tabs() = tabs.now :+ NavigationTab("Buttons", "buttons", "log-in".glyphicon, TestPanel("Serious business panel", PanelStyle.warning))
      navigationBar.selectTab(2)
    })
  }
} 
开发者ID:Karasiq,项目名称:scalajs-bootstrap,代码行数:54,代码来源:BootstrapTestApp.scala

示例8: TestModal

//设置package包名称以及导入依赖的类
package com.karasiq.bootstrap.test.frontend

import com.karasiq.bootstrap.Bootstrap.default._
import org.scalajs.dom.{File, window}
import rx._

import scalaTags.all._

object TestModal {
  def apply(): Modal = {
    val modalInputValue = Var("10000000") // Better use string
    val option2Title = Var("Option 2")
    val radioGroup = FormInput.radioGroup(FormInput.radio("Test1", "modal-title", "First radio"), FormInput.radio("Test2", "modal-title", "Second radio"))
    val select = FormInput.select("Plain select", "Option 1" ? "Option 1", "Option 2" ? option2Title, "Option 3" ? "Option 3")
    val multipleSelect = FormInput.simpleMultipleSelect("Multiple select", "Option 1", "Option 2", "Option 3")
    val files = Var[Seq[File]](Nil)
    files.map(_.headOption).foreach(_.foreach(file ? window.alert(s"File selected: ${file.name}")))

    val form = Form(
      FormInputGroup(FormInputGroup.label("Money"), FormInputGroup.addon("usd".fontAwesome(FontAwesome.fixedWidth)), FormInputGroup.number(modalInputValue.reactiveInput)),
      radioGroup,
      select,
      multipleSelect,
      FormInput.textArea("Money text area", rows := 1, modalInputValue.reactiveInput),
      FormInput.file("Test file", files.reactiveInputRead)
    )

    select.selected() = Seq("Option 2")
    option2Title() = "Changed option 2"

    Modal()
      .withTitle(radioGroup.value, " / ", select.selected.map(_.head), " / ", multipleSelect.selected.map(_.mkString(" + ")))
      .withBody(p("You won ", modalInputValue, "$"), p(form))
      .withButtons(Modal.closeButton(), Modal.button("Take", Modal.dismiss))
      .withDialogStyle(ModalDialogSize.large)
  }
} 
开发者ID:Karasiq,项目名称:scalajs-bootstrap,代码行数:38,代码来源:TestModal.scala

示例9: dontSerialize

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

import play.api.libs.json._

import com.olegych.scastie.api._
import com.olegych.scastie.client.components.Editor

import japgolly.scalajs.react.extra.Reusability

import org.scalajs.dom.window

package object client {

  def dontSerialize[T](fallback: T): Format[T] = new Format[T] {
    def writes(v: T): JsValue = JsNull
    def reads(json: JsValue): JsResult[T] = JsSuccess(fallback)
  }

  def dontSerializeOption[T]: Format[Option[T]] =
    dontSerialize(None)

  def dontSerializeList[T]: Format[List[T]] =
    dontSerialize(List())

  val isMac = window.navigator.userAgent.contains("Mac")
  val ctrl = if (isMac) "?" else "Ctrl"

  implicit val reusability: Reusability[View] =
    Reusability.by_==

  implicit val attachedDomsReuse: Reusability[AttachedDoms] =
    Reusability.byRef ||
      Reusability.by(_.v.keys.toSet)

  implicit val instrumentationReuse: Reusability[Set[Instrumentation]] =
    Reusability.byRefOr_==

  implicit val compilationInfosReuse: Reusability[Set[Problem]] =
    Reusability.byRefOr_==

  implicit val runtimeErrorReuse: Reusability[Option[RuntimeError]] =
    Reusability.byRefOr_==

  implicit val completionsReuse: Reusability[List[Completion]] =
    Reusability.byRefOr_==

  implicit val editorReuse: Reusability[Editor] =
    Reusability.byRef ||
      (
        Reusability.by((_: Editor).attachedDoms) &&
          Reusability.by((_: Editor).instrumentations) &&
          Reusability.by((_: Editor).compilationInfos) &&
          Reusability.by((_: Editor).runtimeError) &&
          Reusability.by((_: Editor).completions)
      )
} 
开发者ID:scalacenter,项目名称:scastie,代码行数:57,代码来源:package.scala

示例10: Page

//设置package包名称以及导入依赖的类
package autosteamgifts.background.options

import autosteamgifts.Implicits._
import org.scalajs.dom.window
import org.scalajs.dom.raw.{Document, HTMLAnchorElement, HTMLElement, HTMLInputElement, HTMLSelectElement}

class Page(document: Document) {
  lazy val form = document.getElementById("form")

  lazy val checkEnableElement = document.query[HTMLInputElement]("#check-enabled")
  lazy val checkIntervalElement = document.query[HTMLSelectElement]("#check-interval")
  lazy val checkActions = document.query[HTMLElement]("#check-actions")

  lazy val hideGamesEnableElement = document.query[HTMLInputElement]("#hide-games")
  lazy val hideGamesBelowPercentRatingElement = document.query[HTMLInputElement]("#hide-games-percent")

  lazy val autoEnterGiveawaysEnableElement = document.query[HTMLInputElement]("#enter-giveaways")

  lazy val notifyEnableElement = document.query[HTMLInputElement]("#notify-ending-giveaways")
  lazy val notifyTimeAmountElement = document.query[HTMLSelectElement]("#notify-time-amount")

  lazy val hideFeaturedGiveawayElement = document.query[HTMLInputElement]("#hide-featured-giveaway")
  lazy val hidePinnedGiveawaysElement = document.query[HTMLInputElement]("#hide-pinned-giveaways")
  lazy val hideActiveDiscussionsElement = document.query[HTMLInputElement]("#hide-active-discussions")

  lazy val repositionIconsElement = document.query[HTMLInputElement]("#reposition-icons")
  lazy val streamlineHidingElement = document.query[HTMLInputElement]("#streamline-hiding")
  lazy val includeEnterButtonElement = document.query[HTMLInputElement]("#include-enter-button")
  lazy val includeRating = document.query[HTMLInputElement]("#include-rating")

  lazy val allInputElements = document.queryAll[HTMLInputElement]("input,select")

  lazy val resourceSavingTipElement = document.query[HTMLElement]("#resource-saving-tip")
  lazy val resourceSavingTipToggleElement = document.query[HTMLElement]("#resource-saving-tip-toggle")

  lazy val hiddenGamesTipElement = document.query[HTMLElement]("#hidden-games-tip")
  lazy val hiddenGamesTipToggleElement = document.query[HTMLElement]("#hidden-games-tip-toggle")

  lazy val streamlineHidingTipElement = document.query[HTMLElement]("#streamline-hiding-tip")
  lazy val streamlineHidingTipToggleElement = document.query[HTMLElement]("#streamline-hiding-tip-toggle")

  lazy val steamGiftsGiveawaysSettingsElements = document.queryAll[HTMLAnchorElement](".steamgifts-giveaways-settings")

  lazy val submitButton = form.query[HTMLInputElement]("input[type='submit'")
  lazy val optionsNotSavedMsgElement = document.query[HTMLElement]("#options-not-saved-msg")
  private lazy val optionsSavedMsgElement = document.query[HTMLElement]("#options-saved-msg")

  def showSavedMsg(): Unit = {
    optionsSavedMsgElement.classList.remove("hidden")

    window.setTimeout({ () =>
      optionsSavedMsgElement.classList.add("hidden")
    }, 1)
  }
} 
开发者ID:erdavila,项目名称:auto-steamgifts,代码行数:56,代码来源:Page.scala

示例11: LoginUser

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

import client.services.{CoreApi, CoreApiOld, LGCircuit}
import diode.{ActionHandler, ActionResult, ModelRW}
import org.scalajs.dom.window
import shared.dtos.UpdateUserRequest
import client.dtos.UserModel
import client.logger
import diode.AnyAction._

import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global

// scalastyle:off
case class LoginUser(userModel: UserModel)

case class LogoutUser()

case class PostUserUpdate(updateUserRequest: UpdateUserRequest)

case class ToggleAvailablity()

class UserHandler[M](modelRW: ModelRW[M, UserModel]) extends ActionHandler(modelRW) {
  //  val messageLoader = "#messageLoader"
  override def handle: PartialFunction[Any, ActionResult[M]] = {
    case LoginUser(userModel) =>
      updated(userModel.copy(isAvailable = true, isLoggedIn = true))

    case LogoutUser() =>
      // todo: Cancel all subscribe request for all sessions
      window.sessionStorage.clear()
      window.location.href = "/"
      updated(UserModel(email = "", name = "", imgSrc = "", isLoggedIn = false))

    case PostUserUpdate(req) =>
      var count = 1
      post()
      def post(): Unit = CoreApiOld.updateUserRequest(req).onComplete {
        case Success(response) =>
          logger.log.debug("user update request sent successfully")
        case Failure(response) =>
          if (count == 3) {
            //            logger.log.error("user update error")
            LGCircuit.dispatch(ShowServerError(response.toString))
          } else {
            count = count + 1
            post()
          }
      }
      if (req.jsonBlob.imgSrc != null) {
        updated(value.copy(imgSrc = req.jsonBlob.imgSrc))
      } else noChange

    case ToggleAvailablity() =>
      updated(value.copy(isAvailable = !value.isAvailable))

  }
} 
开发者ID:francescopersico,项目名称:i,代码行数:59,代码来源:UserHandler.scala

示例12: RefreshProjects

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

import client.modules.AppModule
import diode.{ActionHandler, ActionResult, Effect, ModelRW}
import diode.data._
import shared.models.{ProfilesPost, ProjectsPost}
import org.scalajs.dom.window
import client.rootmodel.ProjectsRootModel
import client.services.{CoreApi, CoreApiOld, LGCircuit}
import diode.util.{Retry, RetryPolicy}
import client.sessionitems.SessionItems
import client.utils.ContentUtils
import org.widok.moment.Moment

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Try

// Actions
case class RefreshProjects(potResult: Pot[ProjectsRootModel] = Empty, retryPolicy: RetryPolicy = Retry(3))
    extends PotActionRetriable[ProjectsRootModel, RefreshProjects] {
  override def next(value: Pot[ProjectsRootModel], newRetryPolicy: RetryPolicy) = RefreshProjects(value, newRetryPolicy)
}

case class ClearProjects()

class ProjectsHandler[M](modelRW: ModelRW[M, Pot[ProjectsRootModel]]) extends ActionHandler(modelRW) {
  override def handle: PartialFunction[Any, ActionResult[M]] = {
    case action: RefreshProjects =>
//      val labels = window.sessionStorage.getItem(SessionItems.ProjectsViewItems.CURRENT_PROJECTS_LABEL_SEARCH)
      val updateF = action.effectWithRetry(CoreApiOld.sessionPing(LGCircuit.zoom(_.session.projectSessionUri).value)) { res =>
        LGCircuit.dispatch(RefreshProjects())
        val currentProjects = if (value.nonEmpty) value.get.projectsModelList else Nil
        val proj = currentProjects ++
          ContentUtils
            .processRes(res)
            .filterNot(_.pageOfPosts.isEmpty)
            .flatMap(content => Try(upickle.default.read[ProjectsPost](content.pageOfPosts(0))).toOption)
        ProjectsRootModel(proj.sortWith((x, y) => Moment(x.created).isAfter(Moment(y.created))))
      }
      action.handleWith(this, updateF)(PotActionRetriable.handler())

    case ClearProjects() =>
      updated(Pot.empty)
  }
} 
开发者ID:francescopersico,项目名称:i,代码行数:46,代码来源:ProjectsHandler.scala

示例13: gui

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

import org.scalajs.dom.{document, window}
import scala.concurrent.duration._
import scala.scalajs.js.timers
import scala.util.Random

object gui {
  def main(args: Array[String]): Unit = {
    val canvas = document.createCanvas
    canvas.width = window.innerWidth.toInt - 10
    canvas.height = window.innerHeight.toInt - 20
    document.body.appendChild(canvas)

    val ctx = canvas.getContext2d

    def drawPoint(point: Point2D): Unit =
      ctx.fillRect(point.x, point.y, 8.0, 8.0)

    def drawMean(mean: Mean[Point2D]): Unit =
      ctx.fillCircle(mean.value, 8.0, "black")

    def drawClusters(clusters: List[Cluster[Point2D]]): Unit =
      clusters.zip(color.randomStream).foreach {
        case (cluster, color) =>
          ctx.fillStyle = color.toString
          cluster.points.foreach(drawPoint)
          drawMean(cluster.mean)
      }

    def animateClusters(steps: Stream[List[Cluster[Point2D]]]): Unit = {
      if (steps.nonEmpty) {
        ctx.clearCanvas()
        drawClusters(steps.head)
        timers.setTimeout(100.millisecond)(animateClusters(steps.tail))
        ()
      }
    }

    implicit val point2dOrdering: Ordering[Point2D] =
      Ordering[(Double, Double)].on(m => (m.x, m.y))

    val count = 2 + Random.nextInt(7)
    val points = List.fill(count)(canvas.randomCluster(1100)).flatten
    val kMeans2D = new KMeans2D
    val steps = kMeans2D.runSteps(count, points).map(_.sortBy(_.mean.value))
    animateClusters(steps)
  }
} 
开发者ID:fthomas,项目名称:kmeans,代码行数:50,代码来源:gui.scala

示例14: RxLocation

//设置package包名称以及导入依赖的类
package com.karasiq.nanoboard.frontend.utils

import org.scalajs.dom
import org.scalajs.dom.window
import org.scalajs.jquery.jQuery
import rx._

import scala.scalajs.js.UndefOr

final class RxLocation(implicit ctx: Ctx.Owner) {
  private def readHash(hash: UndefOr[String]): Option[String] = {
    hash
      .filter(_.nonEmpty)
      .map(_.tail)
      .toOption
  }

  val hash: Var[Option[String]] = Var(readHash(window.location.hash))

  hash.triggerLater {
    window.location.hash = hash.now.fold("")("#" + _)
  }

  jQuery(dom.window).on("hashchange", () ? {
    hash() = readHash(window.location.hash)
  })
}

object RxLocation {
  def apply()(implicit ctx: Ctx.Owner): RxLocation = {
    new RxLocation()
  }
} 
开发者ID:Karasiq,项目名称:nanoboard,代码行数:34,代码来源:RxLocation.scala

示例15: hash

//设置package包名称以及导入依赖的类
package com.karasiq.webmtv.frontend.utils

import org.scalajs.dom.window
import org.scalajs.jquery.jQuery
import rx._

import scala.scalajs.js

sealed trait RxLocation {
  private val _hash: Var[String] = Var(window.location.hash)

  def hash(implicit ctx: Ctx.Owner): Rx[Option[String]] = _hash.map { value ?
    if (js.isUndefined(value) || value.eq(null) || value.isEmpty) {
      None
    } else {
      Some(value.tail)
    }
  }

  jQuery(() ? {
    jQuery(window).on("hashchange", () ? {
      _hash.update(window.location.hash)
    })
  })
}

object RxLocation extends RxLocation 
开发者ID:Karasiq,项目名称:webm-tv,代码行数:28,代码来源:RxLocation.scala


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