2016-11-21 117 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' } 
     }); 
    }); 
});