stimulus(6300✨)

https://github.com/stimulusjs/stimulus

一个现代JS框架,不会完全占据你的前端,事实上它不涉及渲染HTML。

相反,它被设计用于增加你的HTML和刚刚够好的behavior。

 

Stimulus和Turbolinks协作非常好。

Stimulus is a JavaScript framework with modest ambitions. It doesn’t seek to take over your entire front-end—in fact, it’s not concerned with rendering HTML at all. Instead, it’s designed to augment your HTML with just enough behavior to make it shine. Stimulus pairs beautifully with Turbolinks to provide a complete solution for fast, compelling applications with a minimal amount of effort.

 


原文:  https://chloerei.com/2018/02/24/stimulus/

 

它解决了取元素data-target和绑事件data-action的问题. 用 MutationObserver 监控元素的变化, 补绑事件或者修改元素的引用.

这是 Ruby 社区给多页面应用设计的框架。

Stimulus对HTML5页面局部更新支持非常到位,可以说是和RoR的Turbolinks配合最好的JS库。解决了JQuery和Turbolinks配合时,对事件绑定要小心处理的问题。

如果你已经在使用 Turbolinks + SJR(非Ajax),那么可以马上使用 Stimulus,它会让前端代码更规范。

如果前端需求非常复杂,需要处理大量客户端状态,那么应该求助于前端渲染框架(Vue,React)。

如果你的团队已经使用前后端分离的方式开发、不需要 SEO、没有对前后端分裂感到痛苦,那么就不需要 Stimulus。

 


 

At its core, Stimulus’ purpose is to automatically connect DOM elements to JavaScript objects. Those objects are called controllers.

核心,目的是自动连接DOM元素到JS对象。这些JS对象被叫做controllers。

 

Identifiers连接HTML元素和controllers(这里是一个单文件.js组件), 例子;

  <div data-controller="hello">
    <input type="text">
    <button>
      Greet
    </button>
  </div>

 

 

在controllers/hello_controller.js中使用:connect() { console.log()}方法,刷新浏览器,可以看到成功连接上<div>和hello controller

import { Controller } from "stimulus"

export default class extends Controller {
  connect() {
    console.log("Hello, Stimulus!", this.element)
  }
}

 

 

处理事件events的controller方法,叫做action methods

In Stimulus, controller methods which handle events are called action methods.

 

使用data-action来使用event激活action methods。

    <button data-action="click->hello#greet">  //称为action descriptor
      Greet
    </button>
  • click是事件名字
  • hello是controller identifier
  • greet是action method的名字

 

标记重要元素为targets, 通过对应的属性来引用位于controller对象中的它们。

Stimulus lets us mark important elements as targets so we can easily reference them in the controller through corresponding properties.

<input data-target="hello.name" type="text">
  • name是target的name

 

当增加name到controller的target定义的list中后,static targets = ["xxx", ...]

Stimulus自动创建一个this.nameTarget属性,它会返回第一个匹配的target element。

我们可以用这个属性来读取元素的value并创建我们的greeting string

  greet() {
    const element = this.nameTarget
    const name = element.value
    console.log(`Hello, ${name}!`)
  }

 

Controller简化重构:

  static targets = [ "name" ]
  
  greet() {
    console.log(`Hello, ${this.name}!`)  //this是t{context: e} 上下文作用域中的内容。
  }

  get name() {
    return this.nameTarget.value
  }

 

 

Stimulus继续监听网页,当属性变化/消失时,生效。

任何DOM的更新都会让他工作,无论是来自完全的网页加载,或者Turbolinks页面变化,或者Ajax请求。

他Stimulus管理整个lifecycle.

适合小型的团队。

 

什么是 static targets = [ ...]

When Stimulus loads your controller class, it looks for target name strings in a static array called targets.

For each target name in the array, Stimulus adds three new properties to your controller. Here, our "source" target name becomes the following properties:

  • this.sourceTarget evaluates to the first source target in your controller’s scope. If there is no source target, accessing the property throws an error.
  • this.sourceTargets evaluates to an array of all sourcetargets in the controller’s scope.
  • this.hasSourceTarget evaluates to true if there is a source target or false if not.

 

常见事件有默认的action,即可省略。

 

例子:

  <div data-controller="clipboard">
    PIN: <input data-target="clipboard.source" type="text" value="1234" readonly>
    <button data-action="clipboard#copy">
      Copy to Clipboard
    </button>
  </div>

 

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = ["source"]
  copy() {
    this.sourceTarget.select()    //select()方法,用于选择。
    document.execCommand("copy")/copy是Clipboard API中的事件。
  }
}

 

Stimulus Controllers are Reusable

controllers对象是类,可以有多个实例,因此是可以被复用.

比如多个<input data-target="clipboard.source" ...略>

 

Actions and Targets Can Go on Any Kind of Element

Stimulus lets us use any kind of element we want as long as it has an appropriate data-action attribute.

 

 


 

Managing State

Most contemporary frameworks encourage you to keep state in JavaScript at all times. They treat the DOM as a write-only rendering target, reconciled by client-side templates consuming JSON from the server.

大多数现代框架鼓励你用JS始终保持state。它们对待DOM为一个只写入的渲染target,它们由客户端模版调和,消费consume从服务器传入的JSON数据。

Stimulus takes a different approach. A Stimulus application’s state lives as attributes in the DOM; controllers themselves are largely stateless. This approach makes it possible to work with HTML from anywhere—the initial document, an Ajax request, a Turbolinks visit, or even another JavaScript library—and have associated controllers spring to life automatically without any explicit initialization step.

Stimulus使用不同的方法。一个Stimulus程序的state作为DOM的属性而存在;controllers本身是没有状态的。这种方法让Stimulus可以和HTML一起使用在任何地方--最初的document, an Ajax request, a Turbolinks vist, 甚至其他JS库--并且有关联的controllers自动地突然启动,无需任何明确的初始化步骤。

 

一个案例:

1.根元素<div>加上data-controller属性。通过属性值,调用.js文件中的类对象实例化一个对象t {context: e}用于连接到根元素<div>。

2.子元素<div>全部加上data-target="slideshow.slide"。对象t的slideTargets属性的值是一个数组集合,值就是这些子元素.

3.这样就可以顺利的取得这些元素,对它们进行操作,如修改元素的class属性。

4.button元素加上data-acton则绑定event。

本例是通过event,把子元素<div>的class属性display:none修改为display: block。

<div data-controller="slideshow">  
  <button data-action="slideshow#previous">←</button>
  <button data-action="slideshow#next">→</button>

  <div data-target="slideshow.slide" class="slide">🐵</div>
  <div data-target="slideshow.slide" class="slide">🙈</div>
  <div data-target="slideshow.slide" class="slide">🙉</div>
  <div data-target="slideshow.slide" class="slide">🙊</div>
</div>

 

// src/controllers/slideshow_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "slide" ]

  initialize() {      //lifecycle callbacks
    this.showSlide(0)    //this是实例化的对象, showSide()是定义的函数
  }

  next() {
    this.showSlide(this.index + 1)
  }

  previous() {
    this.showSlide(this.index - 1)
  }

  showSlide(index) {
    this.index = index    //声明controller对象的属性index
    this.slideTargets.forEach((el, i) => {
      el.classList.toggle("slide--current", index == i)  //toggle是DOMTokenList中的方法
    })
  }
}

tokenList.toggle(token, force);
如果force是true,则把token加入tokenList中,(true是默认状态,可不加)
如果force是false,如果tokenList中有这个token,则移除。

 

Lifecycle Callbacks 回调。

Method          Invoked by Stimulus…
initialize()    Once, when the controller is first instantiated
connect()       Anytime the controller is connected to the DOM
disconnect()    Anytime the controller is disconnected from the DOM

 

从DOM中读取初始状态state:

根元素<div>中增加data-属性: data-slideshow-index="1",

在.js文件中的initialize(){}:

  initialize() {
    const index = parseInt(this.element.getAttribute("data-slideshow-index"))
    this.showSlide(index)
  }
  // 或者使用const index = parseInt(this.data.get("index")),这是Stimulus的API
  // has(), get(), set()。针对data-*属性操作。 

 

  • this.data.has("index"): 返回boolean

  • this.data.get("index"): 返回index的值。

  • this.data.set("index", xxx): 设置值。

 

Persisting State in the DOM,在DOM中储存state

让controller对象的index属性的值和DOM中储存的index保持同步:

当controller中的index变化时,DOM中的index也同步改变。

方法是

  1. 使用data-***-index对index的值进行储存,  ***是连接的identifier
  2. 对controller对象的index属性改用getter/setter存储机制对属性进行存取。
export default class extends Controller {
  static targets = [ "slide" ]

  initialize() {
    this.showCurrentSlide()
  }

  next() {
    this.index++
  }

  previous() {
    this.index--
  }

  showCurrentSlide(index) {
    this.slideTargets.forEach((el, i) => {
      el.classList.toggle("slide--current", this.index == i)
    })
  }

  get index() {
    return parseInt(this.data.get("index"))
  }

  set index(value) {
    this.data.set("index", value)
    this.showCurrentSlide()
  }
}

 


 

异步加载HTML

使用timer来自动定时刷新:使用setInterval(function, milliseconds)

注意:setTimeout()只能执行一次函数,而setInterval()是反复执行,直到使用clearInterval()。

 

例子:

  <div data-controller="content"
       data-content-url="/messages.html"    //一个html文件。异步加载到这个div内。
       data-content-refresh-interval="5000"></div>  

 

content_controller.js

import { Controller } from "stimulus"

export default class extends Controller {
  connect() {
    this.load()
    
    if(this.data.has("refreshInterval")) {       //驼峰写法 ,在<div>中是-xx-xx
      this.startRefreshing()
    }
  }
  
  startRefreshing() {
    setInterval(()=> {
      this.load()
    }, this.data.get("refreshInterval"))
  }
  
  load() {
    fetch(this.data.get("url"))          //使用Fetch API
      .then(response => {
        console.log(response)
        return response.text()
      })
      .then(html => {
        this.element.innerHTML = html
      })
  }
}

 

fetch()方法:接受一个参数, 这个path是你想要fetch的资源resource。 fetch()返回一个Promise,即对请求的响应response。

 

Release the tracked Resource

当根元素div和controller对象断开连接时,必须停止controller的反复请求行为。

在disconnect()中添加一个this.stopRefresing()函数。

  disconnect() {
    this.stopRefreshing()
  }
  
  startRefreshing() {
    this.refreshTimer = setInterval(()=> {       //把setInterval给refreshTimer属性
      this.load()
    }, this.data.get("refreshInterval"))
    console.log(this)
  }
  
  stopRefreshing() {              //如果refreshTimer属性存在,则证明一直在执行请求
    if (this.refreshTimer) {      
      clearInterval(this.refreshTimer)     //clearInterval()终止.
    }
  }

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2018-10-17 20:29  Mr-chen  阅读(536)  评论(0编辑  收藏  举报