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. vim正则表达式

    目录 一.使用正则表达式的命令[/,?, s, g] 1. 搜索命令 2. 替换命令s 3. global 命令形式 二.正则表达式的用法 表示位置的符号 表示数量的元字符 元字符一览 方括号内的特殊 ...

  2. 【Python基础】zip函数的使用

    zip函数的使用 描述 zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表. 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同, ...

  3. python基础(13)-面向对象

    类 类的定义和使用 # class Person: def __init__(self, name, age, gender): self.name = name self.age = age sel ...

  4. javascript常用的操作

    1.concat()  连接两个或更多的数组,并返回一个新的数组.注意:该方法不会改变原数组 var arry1=["李四",“王二”]:  var arry2=['赵柳',“李旺 ...

  5. ORACLE删除分区

    业务需求:定期删除表中三个月之前的数据 说明:由于表采取一个月一个分区的设计,所以删除三个月之前的数据也就是删除三个月之前的分区.但需要注意的是删除分区后全局索引会失效,而本地local索引不会受到影 ...

  6. MTSC2019第五届中国移动互联网测试开发大会北京站震撼来袭!

    MTSC2019 暨第五届中国移动互联网测试开发大会(Mobile Testing Summit China)是由国内最大的测试开发技术社区之一 TesterHome 发起的行业会议,聚焦于软件测试及 ...

  7. 使用Navicat定时备份mysql数据库和创建报表并邮件自动发送

    数据库备份在现代计算机高速发展的今日变得日益重要,程序员往往因为不重视而忽略备份数据,导致数据丢失,造成非常严重的后果.定时备份无疑是解决备份的最好的途径,本文主要使用Navicat来自动备份数据库和 ...

  8. 3D打印机如何添加自动调平功能

    原理说明 Kossel/Rostock等Delta(并联/三角洲)类型的机器,可以参考:http://learn.makerlab.me/guides/11 3d打印打印时最重要的是第一层的效果,如果 ...

  9. mongodb认识

    MongoDB安装 一.软件的获取地址 1.使用本安装文档提供的安装软件 本安装文档提供的软件为window版本的64位MongoDB的安装包 2.在官网上下载所需的安装软件 下载地址:https:/ ...

  10. python 装饰器(语法糖)

    def  login(func):    def testlogin():        for  i in range(3):            _username="abc" ...