Call function from outside master view model in knockout.js -


i've seen similar topics it, none of them using same structure me.

i using multiple view models , deal creating mastermodel function later on pass argument applybindings.

basically this:

var mastermodel = function(){     this.user = new userviewmodel();     this.department = new departmentviewmodel(); }  ko.applybindings(mastermodel); 

now, able access javascript function inside 1 of view models , i'm having troubles it.

i managed call viewmodel function if change applybindings this:

var mm = new mastermodel(); ko.applybindings(mm);  mm.user.sayhi(); 

but found out things following stop working:

<ul data-bind="foreach: department.list()">      <li data-bind="text: department.getdemo($data)"></li> </ul> 

message: department not defined

reproduction online

and can see here, works when using ko.applybindings(mastermodel);

any solution this?

you need point knockout in right direction in order use department:

<li data-bind="text: $root.department.getdemo($data)"></li> 

when you're inside foreach loop, scope item you're iterating on, , item (obviously) doesn't have department property.

you need use $root tell knockout it's department defined on root view-model you're referring to.

see fiddle , documentation


Comments