Knockout.js calling method outside of view model
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);
If this isn't what you were looking for, let me know!
Phil Ninan
Love to learn new things. programming intrigues me. im young but trying to learn as much as i can! Current languages Java HTML Javascript Wish List MySQL PHP Python Ruby YITBOS
Updated on June 04, 2022Comments
-
Phil Ninan almost 2 years
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!