【bpmn.js 使用总结】八、自定义规则

11 篇文章 37 订阅

自定义 Rules

为 Bpmn 加上新的规则约束。

开始

1. 创建相关文件

老规矩,准备好文件。这里直接从 bpmn-js-examples 中的custom-modeling-rules

建立自定义规则的相关文件,结构如下

| -- rules
    |-- CustomRules.js
    |-- index.js
2. 修改

index.js

import CustomRules from './CustomRules'

export default {
  __init__: ['customRules'],
  customRules: ['type', CustomRules]
}

把注释一去,代码其实并不多。

CustomRules.js

import inherits from 'inherits'

import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider'

export default function CustomRules(eventBus) {
  RuleProvider.call(this, eventBus)
}

inherits(CustomRules, RuleProvider)

CustomRules.$inject = ['eventBus']

CustomRules.prototype.init = function() {
  this.addRule('shape.create', function(context) {
    var shape = context.shape,
      target = context.target
    var shapeBo = shape.businessObject,
      targetBo = target.businessObject

    var allowDrop = targetBo.get('vendor:allowDrop')

    if (!allowDrop || !shapeBo.$instanceOf(allowDrop)) {
      return false
    }
  })
}

可以看到我们 CustomRules 是继承 diagram RuleProvider, 上面代码直接贴是没效果的。
看了下 RuleProvider 源码,
主要看 this.addRule() 这个方法。

/**
 * @param {string|Array<string>} actions the identifier for the modeling action to check
 * @param {number} [priority] the priority at which this rule is being applied
 * @param {Function} fn the callback function that performs the actual check
 */
RuleProvider.prototype.addRule = function (actions, priority, fn) {...}

可以看到是三个参数,所以为this.addRule() 加上 优先级 这个参数就好了。

this.addRule('shape.create', 1234, function(context) {
  // context 根据 context 对象作为判断条件
  // return false // 不通过
  // return true // 通过
  // viod // 也就是无返回,进入下一个规则
})
3. 引用

引入刚刚创建的文件

import customRules from './CustomRules'
export default {
  // ...
  init() {
    this.bpmnModeler = new BpmnModeler({
      additionalModules: [customRules]
    })
    // ...
  }
}
4. 相关规则事件

可以参考里面的事件:BpmnRules,

5.完成

看一下效果,同时阻止了两个事件的发生

this.addRule(['connection.create', 'shape.create'], 1234, function(context) {
  console.log('context', context)
  return false
})

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aaTLf08D-1605883788467)(./img/rules.gif)]

以上只是一个简单的实例。

不能完全阻止元素生成, 因为还有 ContextPad可以生成元素,需要找到阻止他的事件。

最后

rules 案例代码

完整目录: 👉 点击这里

相关

可能对你有帮助的官方资源:

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_pengliang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值