mirror of https://github.com/artf/grapesjs.git
4 changed files with 53 additions and 16 deletions
@ -1,31 +1,59 @@ |
|||
import { keys } from 'underscore'; |
|||
import { Model } from '../../common'; |
|||
import { DataRecordProps } from '../types'; |
|||
import { DataRecordProps, DataSourcesEvents } from '../types'; |
|||
import { DataRecords } from './DataRecords'; |
|||
|
|||
export class DataRecord<T extends DataRecordProps = DataRecordProps> extends Model<T> { |
|||
constructor(props: T, opts = {}) { |
|||
super(props, opts); |
|||
this.on('change', (dr: DataRecord) => { |
|||
const { id, em } = this.dataSource; |
|||
this.on('change', this.handleChange); |
|||
} |
|||
|
|||
const changed = dr.changedAttributes(); |
|||
keys(changed).forEach(prop => { |
|||
const path = this.getPath(prop); |
|||
console.log('TODO change to data:path:DS_ID.DR_ID.KEY ', path); |
|||
em.trigger(path); |
|||
}); |
|||
}); |
|||
get cl() { |
|||
return this.collection as unknown as DataRecords; |
|||
} |
|||
|
|||
get dataSource() { |
|||
return (this.collection as unknown as DataRecords).dataSource; |
|||
return this.cl.dataSource; |
|||
} |
|||
|
|||
get em() { |
|||
return this.dataSource.em; |
|||
} |
|||
|
|||
getPath(prop?: string) { |
|||
const { dataSource, id } = this; |
|||
get index(): number { |
|||
return this.cl.indexOf(this); |
|||
} |
|||
|
|||
handleChange() { |
|||
const changed = this.changedAttributes(); |
|||
keys(changed).forEach(prop => this.triggerChange(prop)); |
|||
} |
|||
|
|||
/** |
|||
* Get path of the record |
|||
* @param {String} prop Property name to include |
|||
* @returns {String} |
|||
* @example |
|||
* const pathRecord = record.getPath(); |
|||
* // eg. 'SOURCE_ID.RECORD_ID'
|
|||
* const pathRecord2 = record.getPath('myProp'); |
|||
* // eg. 'SOURCE_ID.RECORD_ID.myProp'
|
|||
*/ |
|||
getPath(prop?: string, opts: { useIndex?: boolean } = {}) { |
|||
const { dataSource, id, index } = this; |
|||
const dsId = dataSource.id; |
|||
const suffix = prop ? `.${prop}` : ''; |
|||
return `${dsId}.${id}${suffix}`; |
|||
return `${dsId}.${opts.useIndex ? index : id}${suffix}`; |
|||
} |
|||
|
|||
getPaths(prop?: string) { |
|||
return [this.getPath(prop), this.getPath(prop, { useIndex: true })]; |
|||
} |
|||
|
|||
triggerChange(prop?: string) { |
|||
const { dataSource } = this; |
|||
const data = { dataSource, dataRecord: this }; |
|||
this.getPaths(prop).forEach(path => this.em.trigger(`${DataSourcesEvents.path}:${path}`, { ...data, path })); |
|||
} |
|||
} |
|||
|
|||
Loading…
Reference in new issue