cartons
Installation
npm install --save cartons
Documentation
API
Model
构建一个自己的model
Usage
; static key; // key生成函数 默认使用 key-creators.incrementCreator static initialAttributes = test: 1 ; // 每次实例初始化的属性 // attributes set 前的 hook {} // attributes set 后的 hook {}
Static Attributes
- [initialAttributes] {Object|Function} - 建议
Function
设置为Function
时,将会把返回值作为初始化的属性 - key - key生成函数 默认使用
Hooks
- modelWillUpdate {Function(prevAttributes, nextAttributes)} - 调用了
set
, 但还没有执行set
操作时,此时this.get(attributeName) === prevAttributes.get(attributeName)
- modelDidUpdate {Function(prevAttributes, nextAttributes)} - 调用了
set
,set
执行成功, 此时this.get(attributeName) === nextAttributes.get(attributeName)
Arguments
[attributes]
初始化属性 会和static initialAttributes
合并
Method
实例化后可以通过 get
,set
对属性进行读写
var m = ;m // 1mm // 2 var m = test: 3 ;m // 3
Collection
对Model
集合的一层包装, 同时会自动监听所有子Model
的update
事件
; static Model = CustomModel; static key; static initialAttributes = test: 1 ; // hook: before update children (includes remove, add) {} // hook: after update children (includes remove, add) {} // new CustomCollection([initialAttributes], [initialAttributes[]]);var collection = attr2: 2
Static Attributes
- key - 和
model
相同 - [initialAttributes] - 和
model
相同 - [Model] - 用于自动生成子元素的构造函数
Hooks
model
的所有hooks- collectionDidUpdateChildren {Function(prevChildren: Array, nextChildren: Array)} - 添加/删除子元素之前触发
- collectionDidAddChild {Function(prevChildren: Array, nextChildren: Array)} - 添加/删除子元素成功后触发
Arguments
[initialAttributes]
同Model
的initialAttributes
Method
- 可以使用
Array
的各种方法 已支持forEach
,map
,reduce
,reduceRight
,slice
,filter
,find
,findIndex
,some
,every
,includes
,indexOf
collection.forEach((item) => { console.log(item.get('attr3')) }) // 3 // 3
addChild
- 添加一个子元素到最后,并添加监听- @params item {Object} - 子元素属性内容
removeChild
- 移除一个子元素,并取消监听- @params item {Model} - 子元素实例
resetChildren
- 重设所有子元素,并添加监听- @params items {Array}
connect
model
高级用法,关联2个不同的 model
usage
;; ; @ a = ; let b = ;
这样a
被修改的时候,会关联触发b
的update
事件
其他可用的功能
key-creators
现在提供以下几种key生成规则
randomCreator([length = 32], [radix = 16])
生成一个随机数作为key
Arguments
[length = 32]
以2^length
的方式生成一个随机数[radix = 16]
输出的结果的数字基数,默认转换为16进制
incrementCreator(prefix = '')
以递增方式返回key
actions
bindAction(filter: Function|Object)))
usage
@ action1 = action1; model = ; var a = ;a; { // param === 1 return { // model === a.model }}
bindActions(actions: Object.<Function>, options: { actionsAttributeName: string = 'action' })))
usage
@ model = ; var a = ;amodelactions;
createActions()
usage
extend Model @ actions = action1 action2 ...