2016-11-21 114 views
0

免責聲明:道歉lenghty後,我想簡要介紹一下我的問題。如何集中註銷組件註冊?

我已經創建了基本的挖空組件,但它完全正常工作,但我發現,每次我想將我的組件用到其他模板中時,我都需要在它使用之前將它請求到消費者/視圖模型(否則它會抱怨我的組件不知道),這讓我認爲它違反了DRY原則。相反,我希望它成爲淘汰賽的一部分。

場景:myComponent的登記

/*mycomponent registration */ 

define(
[ 
    "knockout", 
    "text!components/my-component-template.htm", 
    "components/my-component-view-model" 
], 
function (ko, myComponentTemplate, MyComponentViewModel) 
{ 
    "use strict"; 

    ko.components.register("mycomponent", 
    { 
     viewModel: 
     { 
      createViewModel: function (params) 
      { 
       return new MyComponentViewModel(params); 
      } 
     }, 

     template: myComponentTemplate 
    }); 
}); 

我通過要求它作爲正常像使用它:

實施例1:

/* template of other consumer */ 

<ul data-bind='normal knockout function'> 
    <li> 
    <a href='#sample-only'></a> 
    <!-- ko component: { name: "mycomponent", params: { data : $data } } --> 
    <!-- /ko --> 
    </li> 
</ul> 

/* other view model 1*/ 

define(
[  
    "knockout", 
    "mycomponent" --> I want to eliminate this and make it part of knockout 
], 
function() 
{ 
    "use strict"; 
    /* Normal coding stuff here */ 
}); 

實施例2:可讓假裝這是樣品不同目的

/* other template that want to use mycomponent */ 
<ul data-bind='other template'> 
    <li> 
    <a href='#sample-only'></a> 
    <!-- ko component: { name: "mycomponent", params: { data : $data } } --> 
    <!-- /ko --> 
    </li> 
</ul> 

/* other view model 2 */ 

define(
[   
    "knockout", 
    "mycomponent" --> I want to eliminate this and make it part of knockout 
], 
function() 
{ 
    "use strict"; 
    /* Normal coding stuff here */ 
}); 

我試圖理解如何custom loader作品進行實驗,並沒有意識到那手工實例的視圖模型通過createViewModel像我上面的例子中的鏈接的例子。然後,我認爲另一種方法是多simplier是創建knockout-extension.js使用它來註冊我的組件和像custome其他淘汰賽文件裝訂處理器等,並要求它在我的index.cshtml象下面這樣:

/* knockout-extension.js */ 
define(
[   
    "<path>/mycomponent" --> Found in Scenario mycomponent registration above 
], 
function() 
{ 
     /* do nothing*/ 
}) 


/* Index */ 

<script type="text/javascript"> 

require({ 
      baseUrl: '@Url.Content("~/Content/js")', 
      waitSeconds: 45, 
      paths: 
      { 
       /* 
       . other dependencies here        
       */ 
       "knockout" : "<path>/knockback-extensions" 
      } 
}); 

但這方法會導致加載超時問題,例如在我無法解決的link中。

有人能擺脫我的小燈或者是這甚至可能嗎?我如何消除需要我的組件的重複,而不是每次都需要消費者,而是我希望它成爲我的淘汰賽的一部分。我希望將註冊集中在一個單獨的文件中,而不需要將其註冊到消費者手中。到目前爲止,這非常痛苦。

回答

0

我得到了一個線索在此link,其中可以要求裏面定義的功能。這解決了我在視圖模型上的問題。

define(
[ 
    "knockout" 
    "require"   
], 
function (ko, require) 
{ 
    "use strict"; 

    require(
    [ 
     "components/my-component-view-model" 
    ], 
    function (MyComponentViewModel) 
    { 
     ko.components.register("mycomponent", 
     { 
      viewModel: 
      { 
       createViewModel: function (params) 
       { 
        return new MyComponentViewModel(params); 
       } 
      }, 

      template: { require : 'text!template-path-here' } 
     }); 
    }); 
});