Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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: http://jsfiddle.net/fourgates/jpk22/1/

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!

like image 920
Phil Ninan Avatar asked Dec 28 '22 03:12

Phil Ninan


1 Answers

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();
userModel.createUsers();

// Use "userModel" to access the methods and properties
// like you're using "self" inside the view model:
userModel.users2()[1].userId(5);

// now apply the binding to THE SAME view model
ko.applyBindings(userModel);

http://jsfiddle.net/jpk22/3/

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

like image 128
Niko Avatar answered Dec 29 '22 16:12

Niko