Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call component function upon initialization in Knockout

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/

like image 345
kspearrin Avatar asked Sep 29 '22 23:09

kspearrin


1 Answers

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/

like image 164
lante Avatar answered Oct 25 '22 07:10

lante