2016-08-05 17 views
0

新的淘汰賽我試圖爲自定義元素構建一個POC。Foreach中的自定義元素沒有料到在淘汰賽中的模型

模型很簡單,MainModel包含一個LinkModel數組。

目標是遍歷鏈接數組以顯示每個LinkModel對象的1個自定義元素「settings-view-link」。

function LinkModel(params) { 
    var self = this; 
    self.name = ko.observable(params.name); 
} 

function MainModel() { 
    var self = this; 
    self.links = ko.observableArray([ 
     new LinkModel({ name: "link1"}), 
     new LinkModel({ name: "link2"}) 
    ]); 
}; 

$(function() { 
    //registration of the custom element 
    ko.components.register('settings-view-link', 
    { 
     viewModel: LinkModel, 
     template: "<div><strong data-bind='text: name'></strong></div>" 
    }); 
    ko.applyBindings(new MainModel()); 
}); 
<div> 
    <ul data-bind="foreach: links"> 
     <p data-bind="text: name"></p> <!-- handled correctly --> 
     <settings-view-link></settings-view-link> <!-- handled not the way I expect--> 
    </ul> 
</div> 

我看到的是,如果在自定義元素,我需要使用$父。讓我的數據綁定按預期工作。使用的

<div><strong data-bind='text: $parent.name'></strong></div> 

代替

<div><strong data-bind='text: name'></strong></div> 

使得出現在我的網頁上鍊接的名字。

我期望在自定義元素內處理一個LinkModel對象,但它不是,它在某種程度上是「子模型」。 有人可以解釋爲什麼我必須使用$父?代碼錯了,但是爲什麼?我真的希望在我的自定義元素中有一個LinkModel對象。

非常感謝

回答

1

因爲你的自定義組件指定viewModel選項,淘汰賽將創建這個視圖模型對您的新實例。您可以省略該屬性,淘汰賽會將組件綁定到提供的參數:

組件通常具有viewmodels,但它們不一定非要。一個組件可以只指定一個模板。在這種情況下,該組件的視圖是綁定的對象是params對象,你傳遞給組件綁定

來源:http://knockoutjs.com/documentation/component-binding.html#note-template-only-components

這個例子可能更好地解釋我的意思。第一個組件指定實例化並綁定到組件實例的視圖模型函數。

第二個組件通過$data作爲參數,基本上作爲模板。如果您不想自動創建新的視圖模型,則可能只需要模板綁定。

var instanceCounter = 0; 
 

 
var ViewModel = function() { 
 
    this.nr = instanceCounter++; 
 
} 
 

 
ko.components.register('testComponent1', { 
 
    viewModel: ViewModel, 
 
    template: '<div data-bind="text: nr"></div>' 
 
}); 
 

 
ko.components.register('testComponent2', { 
 
    template: '<div data-bind="text: nr"></div>' 
 
}); 
 

 

 
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 

 

 
<section> 
 
    <h2>New instance for each component</h2> 
 
    <div data-bind='component: { 
 
    name: "testComponent1" 
 
}'></div> 
 
    <div data-bind='component: { 
 
    name: "testComponent1" 
 
}'></div> 
 
    <div data-bind='component: { 
 
    name: "testComponent1" 
 
}'></div> 
 
</section> 
 

 
<section> 
 
    <h2>Same instance for each component</h2> 
 
    <div data-bind='component: { 
 
    name: "testComponent2", 
 
    params: $data 
 
}'></div> 
 
    <div data-bind='component: { 
 
    name: "testComponent2", 
 
    params: $data 
 
}'></div> 
 
    <div data-bind='component: { 
 
    name: "testComponent2", 
 
    params: $data 
 
}'></div> 
 
</section>

+0

非常感謝它的作品! – Seamus