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">

stimulus(6300✨)的更多相关文章

  1. 动态嵌套form,使用Stimulus Js库(前后端不分离)

    我的git代码:https://github.com/chentianwei411/nested_form-Stimulus- Stimulus:     https://www.cnblogs.co ...

  2. HDU 6300.Triangle Partition-三角形-水题 (2018 Multi-University Training Contest 1 1003)

    6300.Triangle Partition 这个题就是输出组成三角形的点的下标. 因为任意三点不共线,所以任意三点就可以组成三角形,直接排个序然后输出就可以了. 讲道理,没看懂官方题解说的啥... ...

  3. HDU 6300

    Problem Description Chiaki has 3n points p1,p2,…,p3n. It is guaranteed that no three points are coll ...

  4. Hemodynamic response function (HRF) - FAQ

    Source: MIT - Mindhive What is the 'canonical' HRF? The very simplest design matrix for a given expe ...

  5. [Python数据分析]新股破板买入,赚钱几率如何?

    这是本人一直比较好奇的问题,网上没搜到,最近在看python数据分析,正好自己动手做一下试试.作者对于python是零基础,需要从头学起. 在写本文时,作者也没有完成这个小分析目标,边学边做吧. == ...

  6. Verilog笔记——YUV2RGB的模块测试

    1 YUV2RGB的模块如下: module yuv2rgb( clk, //时钟输入 rstn, //复位输入,低电平复位 y_in, //变换前Y分量输出 cb_in, //变换前Cb分量输出 c ...

  7. 使用行为树(Behavior Tree)实现游戏AI

    ——————————————————————— 谈到游戏AI,很明显智能体拥有的知识条目越多,便显得更智能,但维护庞大数量的知识条目是个噩梦:使用有限状态机(FSM),分层有限状态机(HFSM),决策 ...

  8. iTop Webservice列表

    { u'operations':[ { u'verb':u'core/create', u'description':u'Create an object', u'extension':u'CoreS ...

  9. HTML初步入门

    标签元素 标签介绍 html元素包括一个或一对标签定义的包含范围.而标签就是由两个字符串"<"和">"号组成,标签包括开始标签"<& ...

随机推荐

  1. RTOS 和中断之间要注意的

    #define configLIBRARY_LOWEST_INTERRUPT_PRIORITY   15 #define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRI ...

  2. post方式接口测试(二)_参数化

    一.在postman中可设置环境变量和全局变量 二.设置好后直接在请求中使用: 三.get请求,需要将参数直接出现在URL上,直接点击 Params

  3. UI自动化框架——构建思维

    目的:从Excel中获取列的值,传输到页面 技巧:尽可能的提高方法的重用率 Java包: 1.java.core包 3个类:1)日志(LogEventListener)扩展web driver自带的事 ...

  4. RVIZ实现模拟控制小车

    RVIZ是一个强大的可视化工具,可以看到机器人的传感器和内部状态. 1.安装rbx1功能包Rbx1是国外一本关于ros的书中的配套源码,包含了机器人的基本仿真.导航.路径规划.图像处理.语音识别等等. ...

  5. Rosserial实现Windows-ROS交互操作

    安装 sudo apt-get install ros-indigo-rosserial-windows sudo apt-get install ros-indigo-rosserial-serve ...

  6. python基础(6)-深浅拷贝

    赋值 字符串和数字 # id()函数可以获取变量在内存中的地址标识 num1 = 2; num2 = 2; print(id(num1)) # result:8791124202560 print(i ...

  7. Mac下搭建solr搜索引擎与PHP扩展开发(下)

    [接上一篇]https://www.cnblogs.com/rxbook/p/10716759.html [下载php的solr扩展] 现在开始使用php和solr交互了,所以必需安装solr扩展,下 ...

  8. 【Java】NO.80.Note.1.Java.1.001-【Java 各种特性概念】

    1.0.0 Summary Tittle:[Java]NO.80.Note.1.Java.1.001-[Java 各种特性概念] Style:Java Series:Java Since:2018-0 ...

  9. 《More Accurate Question Answering on Freebase》文献笔记

    bast-2015-CIKM CIKM全称是International Conference on Information and Knowledge Management 这篇文章主要采用采用lea ...

  10. Vue使用Typescript开发编译时提示“ERROR in ./src/main.ts Module build failed: TypeError: Cannot read property 'afterCompile' of undefined”的解决方法

    使用Typescript开发Vue,一切准备就绪.但npm start 时,提示“ ERROR in ./src/main.tsModule build failed: TypeError: Cann ...