leakScope
Allow reading the outer scope values from a component’s view and a component’s viewModel values in the user content.
Boolean
false
limits reading to:
- the component’s viewModel from the component’s view, and
- the outer scope values from the user content.
true
adds the ability to read:
- the outer scope values from the component’s view, and
- the component’s ViewModel values from the user content.
The default value is false
.
To change leakScope from the default:
import Component from "can-component";
Component.extend( {
tag: "my-component",
leakScope: true,
ViewModel: { message: { default: "Hello World!" } },
view: "{{message}}"
} );
Leaving leakScope
as the default false
is useful for hiding and protecting
internal details of Component
, potentially preventing accidental
clashes. It can be helpful to set it to true
if you, for example, wanted to customize user content
based on some value in the component’s ViewModel.
Use
A component’s leakScope option controls if a component’s view can access the component’s outer scope and the user content can read the component’s view model.
Let’s define what outer scope, component’s view and user content mean.
If I have a <hello-world>
component in a view like:
{{#data}}
<hello-world>{{subject}}</hello-world>
{{/data}}
The outer scope of <hello-world>
has data
as its context. The user content of
<hello-world>
is the view between its tags. In this case, the user content
is {{subject}}
.
Finally, if <hello-world>
is defined like:
Component.extend( {
tag: "hello-world",
view: "{{greeting}} <content/>{{exclamation}}"
} );
{{greeting}} <content/>{{exclamation}}
represents the component’s view.
Using outer scope in component view
If leakScope
is true
, the component’s view can read the data in the outer scope and will
find name: "John"
in the following example:
Component.extend( {
tag: "hello-world",
leakScope: true, // changed to true instead of the default value
view: "Hello {{scope.find('name')}}"
} );
With this data in the outer scope:
{ name: "John" }
And used like so:
<hello-world />
If leakScope
is true
it will render:
<hello-world>Hello John</hello-world>
If leakScope
is false
it will render:
<hello-world>Hello </hello-world>
Play with this example on JS Bin.
Using viewModel in user content
if leakScope
is true
, the user content is able to see the name property on the component’s
viewModel instance in the following example. Else, name won't be seen.
If the following component is defined:
Component.extend( {
tag: "hello-world",
leakScope: true, // changed to true instead of the default value
ViewModel: { name: { default: "World" } },
view: "Hello <content />"
} );
With this data in the outer scope:
{ name: "John" }
And used like so:
<hello-world>{{name}}</hello-world>
If leakScope
is true
it will render:
<hello-world>Hello World</hello-world>
If leakScope
is false
it will render:
<hello-world>Hello John</hello-world>