我正在尝试编写一个可重用的组件库,并提出了这个问题,这个问题现在困扰着我。
我使用提供的example覆盖了模板引擎。我认为我的问题在他的“关于重写模板的快速说明”中有所提及。段落(我不确定,我的问题可能会有所不同)。但我不知道如何实现它。任何帮助表示赞赏。这就是问题所在:
我的模板引擎基本上注册了以' templateName'和' markUp'。首先,我有一个产品型号,如下:
var Product = function(img, brand, description){
this.img = img;
this.brand = brand;
this.description = description;
};
然后,我的父视图为:
{
name: 'productlist-view',
template: '<productlist-view class="product-list">\
<ul data-bind="foreach: {data: productlist, as: \'product\'}">\
<product-box params="parent: $parent, productInfo: product" data-bind="click: getProduct"></product-box>\
</ul>\
</productlist-view>'
}
现在在此productlist-view
视图的viewModel中,productlist
属性被定义为Product
个实例的数组。 product-box
组件应该为这些Product
中的每一个创建一个viewModel和一个关联的模板。产品盒组件使用以下方式注册到淘汰赛:
ko.components.register('product-box', {
'viewModel': function(params){
this.product = params.product;
this.getProduct = function(){
//Will perform an ajax call here
};
},
'template': '<div class="product-box" data-bind="click: getProduct">\
<img class="product-img fl" data-bind="attr: {src: product.img}"/>\
<p data-bind="text: product.brand"></p>\
<p data-bind="text: product.description"></p>\
</div>'
})
我知道,在上面的代码中,getProduct
方法有两个绑定。我会来的。现在,想象一下productlist-view中的那个不存在。
上面的代码生成一个类似于:
的html<productlist-view ....
<ul ....
<product-box ....
<div class="product-box" ....
<img .../>
<p ... />
<p ... />
</div>
</product-box>
<product-box ..... goes on
</ul>
</productlist-view>
在上面的代码中,div
元素中的包装器the product-box
完全没必要,因为它只是包装了元素。此外,该元素已包含在product-box
元素中。所以我想删除包装div。 这里的问题是,我需要整个产品visual是可点击的,但是我不能将click事件从productlist-view模板绑定到getProduct方法。当foreach
循环迭代时在productlist-view
模板中,$ data指向产品的模型,而不是viewModel
(又称产品框)。
如何从父视图设置此getProduct方法?
有没有在产品盒中删除那个不必要的包装div?
换句话说,我如何拥有一个可点击的产品盒组件,如:
<productlist-view ....
<ul ....
<product-box data-bind="click: getProduct"....
<img .../>
<p ... />
<p ... />
</product-box>
...
</ul>
</productlist-view>
答案 0 :(得分:1)
你可以创建一个自定义绑定处理程序,它将点击绑定附加到父级,但这让我觉得太聪明了一半(并且违反了封装)。如果您的click
绑定与您的组件相关联,则div
成为组件的一部分是有意义的。
您可以使用virtual tag and the component
binding,而不是使用自定义产品标签代码,因此您不会使用无关的包装。