javascriptknockout.jsknockout-components

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/


Solution

  • 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/