2014-09-13 48 views
6

在這種情況下看看:如何訪問Knockout組件中的自定義元素?

ko.components.register('hello', { 
    viewModel: function() { }, 
    template: "<h1>hello wrold</h1>" 
}); 

如果我使用<hello></hello>生成的HTML結果將是:

<hello><h1>hello world</h1></hello> 

但如果我想這樣的:

<hello class="hello"><h1>hello world</h1></hello> 

那麼如何我可以在組件中獲得對自定義元素標記的引用嗎?

回答

11

自定義元素包含該組件,它不被視爲它的一部分。就像foreachtemplatewith中使用的外部標籤一樣。如果您想要設置該標記的樣式,則必須添加綁定來設置它的樣式。該組件將填充其內容。

<hello data-bind="css: 'hello'"></hello> 

但是如果你絕對要訪問的父元素,我想這是可能的,但我不會推薦它。組件應該只關心自己,而不是包含它的容器。如果元素具有任何也具有綁定的子節點,這可能(並且將會)導致問題。

爲您的視圖模型使用工廠函數。它將有權訪問組件的信息(目前僅包含包含元素element

ko.components.register('hello', { 
    viewModel: { 
     createViewModel: function (params, componentInfo) { 
      var element = componentInfo.element; 
      ko.applyBindingsToNode(element, { css: 'hello' }); 
      return {}; 
     } 
    }, 
    template: "<h1>hello world</h1>" 
}); 
相關問題