Skip to content

Component

StefansArya edited this page Jan 7, 2021 · 3 revisions

Components

Components feature is used when you want to create custom element or don't want to have shared model value for each component. Each component will have same structure but the value aren't shared on each element. When defining component name you must use - and word character.

You may like to see the example first.

The usage is pretty similar with sf.model.

sf.component('comp-name', function(My, root, $item){
    My.data = "text";

    // If you're using sf-repeat-this for this component
    // `$item` will have your item value instead of undefined

    // My.$el[0] <-- Contain the current element
    // My.$el('selector') <-- Shortcut to My.$el.find()
    // $('model-name') <-- Get another element from DOM include this

    My.init = function(){
        // When element was initialized
    }

    My.destroy = function(){
        // When element was removed from DOM
        // This have an delay ~0.5s before being called
    }
});

Above method will only create structure, and you need to create template for it.

sf.component.html('comp-name', `<div>{{ data }}</div>`);

You can also create dynamic component template on the DOM.
When using component, you can directly use mustache instead wrapping it to an element first.

<html>
  <body>
    <comp-name>
      {{ data }}
    </comp-name>
  </body>
</html>

After you have define the template you can create the element directly on the DOM like below.

<comp-name></comp-name>

Or you can create new component from the JavaScript like below.

var myElement = new $CompName($item = undefined);
document.body.appendChild(myElement);

// You can access the model with
var model = myElement.model;

myElement will be HTMLElement and you can also access the model scope with myElement.model. It also would be easy to obtain the component scope from the console with $('comp-name')[0].model.

The component data will be automatically removed after the element was deleted. Just make sure you're not saving any reference outside it's scope so everything could be garbage collected.

Clone this wiki locally