viewModel
Return the view model instance or type with which the component’s view is rendered. This is used when more fine grained control is needed over ViewModel.
function(properties, parentScope, element)
The viewModel
function takes the properties
and values that are used to
typically initialize a ViewModel, the
can-view-scope the component is rendered within, and the component’s element
and returns either the view-model instance or ViewModel type that the component’s view
is rendered with.
This is typically used only for special situations where a custom scope or custom bindings need to be setup.
var Component = require("can-component");
var Scope = require("can-view-scope");
Component.extend({
tag: "my-element",
viewModel: function(properties, scope, element){
var vm = new DefineMap(properties);
// do special stuff ...
return vm;
}
});
stache("<my-element first:from='firstName' last='Meyer'/>")({
firstName: "Justin",
middleName: "Barry"
});
Parameters
- properties
{Object}
:An object of values specified by the custom element’s attributes. For example, a view rendered like:
stache("<my-element title:from='name'></my-element>")({ name: "Justin" });
Creates an instance of following control:
Component.extend({ tag: "my-element", viewModel: function(properties){ properties.title //-> "Justin"; } });
And calls the viewModel function with
properties
like{title: "Justin"}
. - parentScope
{can-view-scope}
:The viewModel the custom tag was found within. By default, any attribute’s values will be looked up within the current viewModel, but if you want to add values without needing the user to provide an attribute, you can set this up here. For example:
Component.extend({ tag: "my-element", viewModel: function(properties, parentScope){ parentScope.get('middleName') //-> "Barry" } });
Notice how the
middleName
value is looked up inmy-element
’s parent scope. - element
{HTMLElement}
:The element the can-component is going to be placed on. If you want to add custom attribute handling, you can do that here. For example:
Component.extend({ tag: "my-element", viewModel: function(properties, parentScope, el){ var vm = new DefineMap({clicks: 0}); domEvent.addEventListener.call(el, "click", function(){ vm.clicks++; }); return vm; } });
This example should be done with the events object instead.
Returns
{Map|Object}
:
Returns one of the following.
- An observable map or list type.
- The prototype of an observable map or list type that will be used to render the component’s view.