Javascript – Knockout.js calling method outside of view model


I want to make my data accessible outside of my view model. So I created a view model object but I'm having trouble binding its properties. Note that everything is working properly inside my view model.

Basically a simplified pseudo-code:

function Users() {

function userHealthModel() {
     function createUsers() { new Users[] };

self.userModel = ko.observable(new userHealthModel());

If I call the createUsers method inside my model my bind works fine.

Here is a jsFiddle, note my problem is all the way at the end of the JS, I commented it:

I'm new to JS and KO. not really sure how to use $root, $parent, etc. Please help a fellow programming enthusiast! Many thanks in advance!

Best Solution

I'm still not 100% sure if I understand what you're trying to do, but here are some thoughts about the code in your fiddle:

If you have something like

var self = this;

in the global scope (= not in a function), this points to the window object. Therefore this does not make any sense.

self.userModel = ko.observable(new userHealthModel());

Creating an observable of a view model is not necessary - you don't expect the whole model to change, right? It will always stay a user model and not suddenly become a "message model" or whatever.

If you want to call a method of your view model from the outside, just make an instance:

var userModel = new userHealthModel();

// Use "userModel" to access the methods and properties
// like you're using "self" inside the view model:

// now apply the binding to THE SAME view model

If this isn't what you were looking for, let me know!

Related Question