With a normal view model I can call a function after initialization outside of it's context like so:
var ViewModel = function () {
this.Foo = function () {
alert("bar");
};
};
var vm = new ViewModel();
ko.applyBindings(vm);
vm.Foo();
How do I do something like this with a component's view model? I want to call FooComponentViewModel
's Foo
function when the foo component is first loaded.
ko.components.register("foo", {
viewModel: FooComponentViewModel,
template: {
element: "component-foo"
}
});
function FooComponentViewModel(params) {
this.Foo = function () {
alert("bar");
};
}
var ViewModel = function () {
// empty
};
var vm = ViewModel();
ko.applyBindings();
Just an idea, pass a callback as a parameter for the component:
HTML:
<foo params="callback: callback"></foo>
JS:
function FooComponentViewModel(params) {
this.Foo = function () {
alert("bar");
};
params.callback(this);
}
function ViewModel() {
this.callback = function(vm) {
vm.Foo();
};
}