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. javascript call apply

    call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向.因为 JavaScript 的函数存在「定义时上下文」和「 ...

  2. RNN Train和Test Mismatch

    李宏毅深度学习 https://www.bilibili.com/video/av9770302/?p=8 在看RNN的时候,你是不是也会觉得有些奇怪, Train的过程中, 是把训练集中的结果作为下 ...

  3. Linux下配置Redis集群模式

    配置机器1 在演示中,172.16.179.130为当前ubuntu机器的ip 在172.16.179.130上进⼊Desktop⽬录,创建conf⽬录 在conf⽬录下创建⽂件7000.conf,编 ...

  4. [LeetCode] 系统刷题2_排列组合

    要用到backtracking,是否要跟backtracking放到一起总结? 适用范围: 几乎所有搜索问题 什么时候输出 哪些情况需要跳过 相关题目: [LeetCode] 78. Subsets ...

  5. Cocos Creator 加载和切换场景(官方文档摘录)

    Cocos Creator 加载和切换场景(官方文档摘录) 在 Cocos Creator 中,我们使用场景文件名( 可以不包含扩展名)来索引指代场景.并通过以下接口进行加载和切换操作: cc.dir ...

  6. 屏幕适配(UGUI)非UI

    using UnityEngine; public enum Suit_UIType { Background, Effect, } [RequireComponent(typeof(Transfor ...

  7. 将指定世界中的指定位置的Block转化为箱子

    在bukkit中,block可以操作所有的三位像素方块,如果是向对block进一步操作,我们就需要得到BlockState, BlockState表示一个方块的状态,才能够对方块进行位置等状态的操作, ...

  8. pageresponse.min.js自动缩放页面改写

    /* * 名称 :移动端响应式框架 * 作者 :白树 http://peunzhang.cnblogs.com * 版本 :v2.1 * 日期 :2015.10.13 * 兼容 :ios 5+.and ...

  9. sparse-table模板

    预处理: void init(int n) { ;i < n;i++) { dp[i][] = a[i]; } int bitn = (int)(log(n)/log(2.0)); ;j < ...

  10. 软件工程实践小项目之模拟wc.exe的小程序

    github源码和工程文件地址:https://github.com/Jackchenyu/Word_counts/tree/smart 基本要求:要实现wc的基本功能即文件中字符数.单词数.行数的统 ...