2

我有2個交叉引用的型號。這可能是這樣的:2個型號的交叉引用

MainModel:

define(
    [ 'durandal/app', 'durandal/plugins/router', 'models/Shell', 'models/EditModel' ], 
    function (app, router, shell, editModel) { 
     //... 
     return { 
      //... 

      // This function should be accessible by the EditModel 
      update: function() { 
       //... 
      }, 

      showEditView: function() { 
       // Initialise the EditModel with some data and show the according view afterwards 
       editModel.init('set some important stuff here...'); 
       router.navigateTo('#/EditView'); 
      } 
      //... 
     }; 
    } 
); 

EditModel:

define(
    [ 'durandal/app', 'durandal/plugins/router', 'models/Shell', 'models/MainModel' ], 
    function (app, router, shell, mainModel) { 
     //... 
     return { 
      //... 

      // This function should be accessible by the MainModel 
      init: function() { 
       //... 
      }, 

      showMainView: function() { 
       // Update the the MainModel with some data and show the according view afterwards 
       mainModel.update('set new data here...'); 
       router.navigateTo('#/MainView'); 
      } 
      //... 
     }; 
    } 
); 

可惜,這是行不通的。如果我在MainView上加載我的頁面並調用showEditView,則變量editView是已知的,並且一切正常,但是EditModel中的變量mainModel未定義,因此調用mainModel.update(...)失敗。 如果我在EditView上加載我的頁面,但在「相反方向」(EditModel中的var mainModel已知,但MainModel中的editModel未定義),則會發生同樣的事情。

這是一個已知的問題,如果是這樣的話:我怎樣才能繞過它?

我也貼在Durandals Google Group

感謝

回答

2

檢查requierejs文檔循環依賴http://requirejs.org/docs/api.html#circular這個問題。

循環依賴很少見,通常表示您可能想要 重新考慮設計。但是,有時需要它們,並且在這種情況下,使用require(),如上所述。

對於main.js添加require作爲依賴關係,然後明確要求models/EditModel應該這樣做。要麼複製其他模塊或rethink the design ;-)。

define(
    [ 'require', 'durandal/app', 'durandal/plugins/router', 'models/Shell', 'models/EditModel' ], 
    function (require, app, router, shell, editModel) { 
     //... 
     return { 
      //... 

      // This function should be accessible by the EditModel 
      update: function() { 
       //... 
      }, 

      showEditView: function() { 
       // Initialise the EditModel with some data and show the according view afterwards 
       require('models/EditModel').init('set some important stuff here...'); 
       router.navigateTo('#/EditView'); 
      } 
      //... 
     }; 
    } 
);