Skip to content
StefansArya edited this page Jan 19, 2021 · 2 revisions

This feature is useful for creating your work as distributable model and component w/o doing any scripting. It allow developers that using ScarletsFrame to plug and play the namespace into their template. This would be more easier if you using the framework's compiler.

Creating new namespace

Usually you will need to write this on local scope with ;(function(){ ... })(); to avoid some variable exposed to global scope.

var myNamespace = new sf.Space('my-namespace', {
    onCreate:function(elem){
        // Let's insert default template for <sf-space>
        // when this function called, elem is HTMLElement
    },

    // You can also use template path from `window.templates`
    templatePath:'/index.html'
});

Register new model or component

You can use that myNamespace variable for creating new model/component.

myNamespace.model('theModel', function(My, root){
    // Just like sf.model()
});

myNamespace.component('comp-name', function(My, root, $item){
    // Just like sf.component()
});

// Write component HTML here, maybe..
myNamespace.component('comp-name', '<div>...</div>') // Just like sf.component.html()

Create/Obtain different scope for the namespace

With one namespace you can build many element that have different scope for shared model or component. Every namespace have it's own index, if it doesn't have then it would be an empty string.

// Different index will create/obtain a scope by it's index
var html = myNamespace.createHTML(/* index | empty string */);
document.body.appendChild(html);

var scope = myNamespace.getScope(/* index | empty string */);
var model = scope('theModel');
var componentsList = scope('comp-name');

Any component/model inside <sf-space> will running with that namespace.

<sf-space my-namespace>
    <sf-m name="theModel"></sf-m>
    <comp-name></comp-name>
</sf-space>

Using component from namespace

Because browser the custom element declaration is limited, every component constructor are saved on window even it's registered from different namespace. But single component constructor can be used to create the registered component from different namespace. For the example we already defined our comp-name in myNamespace and want to create component from executable mustache.

<div sf-each="val in list">
   {{@exec
      var doing = "something";

      // new <comp-name>(<item>, <sf.Space>, asScope?)
      @return new $CompName(val, myNamespace, true);
   }}
</div>

Destroy namespace

To destroy an namespace index you just need to remove the element, but make sure that nothing are saved at global scope or somewhere to prevent memory leak.

But if you want to destroy the entire namespace, you can call .destroy() function and it will remove all related the element and also the namespace.

myNamespace.destroy();