简体   繁体   中英

Durandal: Create function in one child and Consume from another child

I have a Knockout application developed using Durandal.JS . Here is the structure of my project:

- Parent
    - Index.js
    - Index.html
- Child1
    - Index.js
    - Index.html
- Child2
    - Index.js
    - Index.html

I have a function UpdateData() declared in Child2/Index.js and I want to consume that function from Child1/Index.js

Reason of declaring this function in Child2 is, I have other variables and controls declared in Child2. And by calling UpdateData() method, I want to update the value of all variables declared in Child2.

I don't know how to handle this situation.

Durandal by default uses require to load modules. You could try to require the child2 module in your child1 module.

//child1 module
define(function (require) {

//require child2 into the module
var child2 = require('Child2/Index');

//use the method
child2.UpdateData();
});

For this to work, you must return the UpdateData() method from Child2 .

//child2 module
define(function(){
return {
UpdateData:function(){
  //your method
}
}});

For more information, you could go through the docs on how to create a module that can be reused by other modules. http://durandaljs.com/documentation/Creating-A-Module.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM