16 KiB
Component
The Component object represents a single node of our template structure, so when you update its properties the changes are immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all the tree of nodes). An example on how to update properties:
component.set({
tagName: 'span',
attributes: { ... },
removable: false,
});
component.get('tagName');
// -> 'span'
Properties
typeString? Component type, eg.text,image,video, etc.tagNameString? HTML tag of the component, eg.span. Default:divattributesObject? Key-value object of the component's attributes, eg.{ title: 'Hello' }Default:{}nameString? Name of the component. Will be used, for example, in Layers and badgesremovableBoolean? Whentruethe component is removable from the canvas, default:truedraggable(Boolean | String)? Indicates if it's possible to drag the component inside others. You can also specify a query string to indentify elements, eg.'.some-class[title=Hello], [data-gjs-type=column]'means you can drag the component only inside elements containingsome-classclass andHellotitle, andcolumncomponents. Default:truedroppable(Boolean | String)? Indicates if it's possible to drop other components inside. You can use a query string as withdraggable. Default:truebadgableBoolean? Set to false if you don't want to see the badge (with the name) over the component. Default:truestylable(Boolean | Array<String>)? True if it's possible to style the component. You can also indicate an array of CSS properties which is possible to style, eg.['color', 'width'], all other properties will be hidden from the style manager. Default:truestylable-requireArray<String>? Indicate an array of style properties to show up which has been marked astoRequire. Default:[]unstylableArray<String>? Indicate an array of style properties which should be hidden from the style manager. Default:[]style-signatureArray<String>? This option comes handy when you need to remove or export strictly component-specific rules. Be default, if this option is not empty, the editor will remove rules when there are no components, of that type, in the canvas. Eg. '['.navbar', '[navbar-']'. Default:''highlightableBoolean? It can be highlighted with 'dotted' borders if true. Default:truecopyableBoolean? True if it's possible to clone the component. Default:trueresizableBoolean? Indicates if it's possible to resize the component. It's also possible to pass an object as options for the Resizer. Default:falseeditableBoolean? Allow to edit the content of the component (used on Text components). Default:falselayerableBoolean? Set tofalseif you need to hide the component inside Layers. Default:trueselectableBoolean? Allow component to be selected when clicked. Default:truehoverableBoolean? Shows a highlight outline when hovering on the element iftrue. Default:truevoidBoolean? This property is used by the HTML exporter as void elements don't have closing tags, eg.<br/>,<hr/>, etc. Default:falsecontentString? Content of the component (not escaped) which will be appended before children rendering. Default:''iconString? Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string ''. Default:''script(String | Function)? Component's javascript. More about it here. Default:''script-export(String | Function)? You can specify javascript available only in export functions (eg. when you get the HTML). If this property is defined it will overwrite thescriptone (in export functions). Default:''traitsArray<(Object | String)>? Component's traits. More about it here. Default:['id', 'title']propagateArray<String>? Indicates an array of properties which will be inhereted by all NEW appended children. For example if you create a component likes this:{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }and append some new component inside, the new added component will get the exact same properties indicated in thepropagatearray (and thepropagateproperty itself). Default:[]toolbarArray<Object>? Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). Eg.toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]. By default, whentoolbarproperty is falsy the editor will add automatically commands likemove,delete, etc. based on its properties.componentsCollection<Component>? Children components. Default:null
init
Hook method, called once the model is created
updated
Hook method, called when the model has been updated (eg. updated some model's property)
Parameters
propertyString Property name, if triggered after some property updatevalueany Property value, if triggered after some property updatepreviousany Property previous value, if triggered after some property update
removed
Hook method, called once the model has been removed
is
Check component's type
Parameters
typestring Component type
Examples
component.is('image')
// -> false
Returns Boolean
props
Return all the propeties
Returns Object
index
Get the index of the component in the parent collection.
Returns Number
setDragMode
Change the drag mode of the component. To get more about this feature read: https://github.com/artf/grapesjs/issues/1936
Parameters
valueString Drag mode, options: 'absolute' | 'translate'
Returns this
find
Find inner components by query string. ATTENTION: this method works only with already rendered component
Parameters
queryString Query string
Examples
component.find('div > .class');
// -> [Component, Component, ...]
Returns Array Array of components
findType
Find all inner components by component id.
The advantage of this method over find is that you can use it
also before rendering the component
Parameters
idString Component id
Examples
const allImages = component.findType('image');
console.log(allImages[0]) // prints the first found component
closest
Find the closest parent component by query string. ATTENTION: this method works only with already rendered component
Parameters
querystring Query string
Examples
component.closest('div.some-class');
// -> Component
Returns Component
replaceWith
Replace a component with another one
Parameters
Examples
component.replaceWith('<div>Some new content</div>');
// -> Component
Returns (Component | Array<Component>) New added component/s
setAttributes
Update attributes of the component
Parameters
attrsObject Key value attributesopts(optional, default{})
Examples
component.setAttributes({ id: 'test', 'data-key': 'value' });
Returns this
addAttributes
Add attributes to the component
Parameters
attrsObject Key value attributes
Examples
component.addAttributes({ 'data-key': 'value' });
Returns this
getStyle
Get the style of the component
Returns Object
setStyle
Set the style on the component
Parameters
propObject Key value style object (optional, default{})opts(optional, default{})
Examples
component.setStyle({ color: 'red' });
Returns Object
getAttributes
Return all component's attributes
Returns Object
addClass
Add classes
Parameters
Examples
model.addClass('class1');
model.addClass('class1 class2');
model.addClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array Array of added selectors
setClass
Set classes (resets current collection)
Parameters
Examples
model.setClass('class1');
model.setClass('class1 class2');
model.setClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array Array of added selectors
removeClass
Remove classes
Parameters
Examples
model.removeClass('class1');
model.removeClass('class1 class2');
model.removeClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array Array of removed selectors
getClasses
Returns component's classes as an array of strings
Returns Array
append
Add new component children
Parameters
components(Component | String) Component to addoptsObject Options, same as inmodel.add()(from backbone) (optional, default{})
Examples
someComponent.get('components').length // -> 0
const videoComponent = someComponent.append('<video></video><div></div>')[0];
// This will add 2 components (`video` and `div`) to your `someComponent`
someComponent.get('components').length // -> 2
// You can pass components directly
otherComponent.append(otherComponent2);
otherComponent.append([otherComponent3, otherComponent4]);
Returns Array Array of appended components
components
Set new collection if components are provided, otherwise the
current collection is returned
Parameters
Examples
// Set new collection
component.components('<span></span><div></div>');
// Get current collection
const collection = component.components();
console.log(collection.length);
// -> 2
Returns (Collection | Array<Component>)
parent
Get the parent component, if exists
Examples
component.parent();
// -> Component
Returns Component
getTrait
Get the trait by id/name
Parameters
idString Theidornameof the trait
Examples
const traitTitle = component.getTrait('title');
traitTitle && traitTitle.set('label', 'New label');
Returns Trait Trait model
updateTrait
Update a trait
Parameters
Examples
component.updateTrait('title', {
type: 'select',
options: [ 'Option 1', 'Option 2' ],
});
Returns this
getTraitIndex
Get the trait position index by id/name. Useful in case you want to replace some trait, at runtime, with something else.
Parameters
idString Theidornameof the trait
Examples
const traitTitle = component.getTraitIndex('title');
console.log(traitTitle); // 1
Returns Number Index position of the current trait
removeTrait
Remove trait/s by id/s.
Parameters
Examples
component.removeTrait('title');
component.removeTrait(['title', 'id']);
Returns Array Array of removed traits
addTrait
Add trait/s by id/s.
Parameters
trait(String | Object | Array<(String | Object)>) Trait to add (or an array of traits)optsOptions Options for the add (optional, default{})
Examples
component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index)
component.addTrait({
type: 'checkbox',
name: 'disabled',
});
component.addTrait(['title', {...}, ...]);
Returns Array Array of added traits
getName
Get the name of the component
Returns String
getIcon
Get the icon string
Returns String
toHTML
Return HTML string of the component
Parameters
optsObject Options (optional, default{})
Examples
// Simple HTML return
component.set({ tagName: 'span' });
component.setAttributes({ title: 'Hello' });
component.toHTML();
// -> <span title="Hello"></span>
// Custom attributes
component.toHTML({ attributes: { 'data-test': 'Hello' } });
// -> <span data-test="Hello"></span>
// Custom dynamic attributes
component.toHTML({
attributes(component, attributes) {
if (component.get('tagName') == 'span') {
attributes.title = 'Custom attribute';
}
return attributes;
},
});
// -> <span title="Custom attribute"></span>
Returns String HTML string
getId
Return the component id
Returns String
setId
Set new id on the component
Parameters
idStringopts
Returns this
getEl
Get the DOM element of the component. This works only if the component is already rendered
Returns HTMLElement
getView
Get the View of the component. This works only if the component is already rendered
Returns ComponentView
onAll
Execute callback function on itself and all inner components
Parameters
clbFunction Callback function, the model is passed as an argument
Examples
component.onAll(component => {
// do something with component
})
Returns this
remove
Remove the component
Returns this
getList
The list of components is taken from the Components module. Initially, the list, was set statically on the Component object but it was not ok, as it was shared between multiple editor instances
Parameters
model
checkId
This method checks, for each parsed component and style object (are not Components/CSSRules yet), for duplicated id and fixes them This method is used in Components.js just after the parsing
Parameters
componentsstyles(optional, default[])list(optional, default{})