5

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();

http://jsfiddle.net/h01ky3pv/

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();

http://jsfiddle.net/r3d41q6c/2/

lante
  • 7,192
  • 4
  • 37
  • 57
kspearrin
  • 10,238
  • 9
  • 53
  • 82

1 Answers1

4

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();
    };
}

http://jsfiddle.net/r3d41q6c/3/

lante
  • 7,192
  • 4
  • 37
  • 57
  • Never thought about this. Good idea! Will wait a few to see if any other ideas. Thanks – kspearrin Jan 20 '15 at 03:07
  • What about cases when we want to invoke method of component. Let our ComponentVm exposes method doSmth(arg1, arg2). Do you have any thoughts about how get access to this method outside component according to knockout ideology? – DotNetter Jan 18 '16 at 10:02