2014-02-18 64 views
0

我的基諾視圖模型變得相當大,我有幾個可觀察的功能和事件處理程序與屬性BillingAddress有關。基因敲除:在單一屬性中的環形守衛觀察

例如,我有

self.BillingAddressEdit 
self.BillingAddressEditMode 
self.BillingAddressAddNew 
self.BillingAddressAddNewMode 
self.BillingAddresses 
self.BillingAddressesLoading 

...和其他幾個人。

我想要做的是將這些收集到一個BillingAddress對象(或函數?)中,該對象具有與屬性相同的觀察值。

因此,一些有效的這樣

self.BillingAddress = { // or possibly function() { 
    AddNew: ko.observable(), 
    AddNewMode: ko.observable(), 
    Addresses: ko.observableArray(), 
    Edit: ko.observable(), 
    EditMode: ko.observable(), 
    Loading: ko.observable() 
} 

和訪問這些視圖上像這樣

<tagName data-bind="foreach: BillingAddress.Addresses"> 
</tagName> 

要做到這一點,什麼形式將這種BillingAddress對象或函數把我現有的視圖模型內?

+0

在淘汰賽網站這個例子可能是有用的:http://knockoutjs.com/examples/collections.html和這裏的相關的jsfiddle HTTP: //jsfiddle.net/rniemeyer/GSvnh/,你可以分叉和修改更改名稱和孩子到BillingAddress和地址 – Tanner

回答

1

在你的情況下,BillingAddress可以是一個單一的對象。當您的子視圖模型多次使用時,該函數是有用的,例如在根模型中的observableArray

更新:

self變量是用來記住視圖模型的上下文。當你有一些回調時,它是有用的,它可以有自己的上下文。

在你的情況你的模型可以是這樣的:

var BillingAddressViewModel = { 
    AddNew: ko.observable(), 
    AddNewMode: ko.observable(), 
    Addresses: ko.observableArray(), 
    Edit: ko.observable(), 
    EditMode: ko.observable(), 
    Loading: ko.observable() 
} 

function RootViewModel() { 
    var self = this; 
    self.BillingAddress = BillingAddressViewModel; 
} 
+0

你能給我一個如何寫出這個例子嗎?例如,我在問題中的例子是否正確?每個屬性應該有「self.」前綴嗎? – awj

+0

@awj我已經更新了答案。 – alexmac

+0

好的,我會盡快發佈並儘快報告。 – awj