0

I'm using KnockoutJS to develop a plugin based on viewmodels. Is there any way to access the functions and properties of another viewmodel running in the same application? Something like this:

My view model:

    function myViewModel()
    {
        this.prop1 = ko.observable(123);
        this.prop2 = ko.observable("Hello");
        ..
        ..
    }

    myViewModel.prototype.func1 = function() {
        //do something...
    };

    myViewModel.prototype.func2 = function() {
        //do something...
    };

And the other view model:

    function otherViewModel()
    {
        this.propA = ko.observable(456);
        this.propB = ko.observable("Goodbye");
        ..
        ..
    }

    otherViewModel.prototype.funcA = function() {
        //do something...
    };

    otherViewModel.prototype.funcB = function() {
        //do something...
    };

The observables of the otherViewModel control certain common functions like pop-ups and masks. Is there any way to instantiate otherViewModel in myViewModel and set those properties?

Or is there any way to globally get and set them?

Please tread lightly as I'm very new to this paradigm. Thank you.

iSofia
  • 1,412
  • 2
  • 19
  • 36
  • Hmm, this is a *very* broad question. You should read about closures, scopes, and oo-style JS programming. For a more practical approach, carefully go through [the knockoutjs tutorials](http://learn.knockoutjs.com/) as well as the documenation. There are many examples in there where dependencies are created between view models. – Jeroen Oct 25 '14 at 13:03

1 Answers1

0

I agree with the comment to use scopes - but there are a couple of quick and dirty ways...

when you instantiate myViewModel - you could instantiate it on the window - and then reference it directly

window.myViewInstance = new myViewModel()

function myOtherViewModel () {
  this.propA = myViewInstance.xyz
}

I use this method when I have something that provides global functionality that I want to use elsewhere. Its what jQuery and ko do... bind $ and ko to the window.

if myViewModel.xyz = ko.observable() then passing it without parens passes it as an observable - which will change as its value changes. With the parens will pass the result at the time it is evaluated.

Alternatively - you can reference it using ko.dataFor like this.

myViewModel () {...}
instance = new myViewModel
ko.applyBindings(instance, $('div')[0])
// this applies bindings of myViewModel to the first div on the page only

myOtherViewModel () {

  this.propA = ko.dataFor($('div')[0])
  // passes the entire object
  this.propB = ko.dataFor($('div')[0]).xyz
  // gives you just one property

}

Which would scope your object to just a part of the page

kikanga
  • 41
  • 2