2013-02-13 41 views
2

是否可以在不改變上下文的情況下使用foreach綁定?在不改變上下文的情況下使用foreach綁定Knockout.js

例如,這裏是我的模板:

<div data-bind="foreach:{data:users,as:'user'}"> 
    <div data-bind="template:{name:'userAvatar',data:user}"></div> 
</div> 

<div data-bind="template:{name:'userAvatar',data:currentUser}"></div> 

<script type="text/template" id="userAvatar"> 
    <img data-bind="attr:{src:avatarUrl}"> 
</script> 

於是我就用模板「userAvatar」 foreach循環內部和外部的。現在我想在用戶點擊頭像時執行一些操作。例如,我的模型是

var MyModel = function() { 
    this.users = [ 
    {name:"user1",avatarUrl:"url1"}, 
    {name:"user2",avatarUrl:"url2"} 
    ]; 
    this.currentUser = {name:"user3",avatarUrl:"url3"}; 
    this.openProfile = function() { 
    // opening user profile 
    } 
} 

這種情況下,如果我想稱之爲「openProfile」模板動作我必須使用$ parent.openProfile當模板位於外的foreach和$家長[1] .openProfile,當它在裏面。

我可以複製鏈接到openProfile到每個用戶對象或指定openProfile方法的位置,當我調用模板綁定,但是有沒有更自然的解決方案?

P.S.而且我不能使用$ root變量,因爲在現實世界中,我的$ root根目錄位於這些模型之上的10個級別。

+0

這是一個例子,在這裏我可以用$根,但在真實情況我有多個嵌套模型,所以我的$ root很遠,它甚至不知道當前的模型及其方法。 – Kasheftin 2013-02-13 13:00:28

+0

我知道這是一個黑客,但你可以在當前用戶tempalte周圍使用'with' ...'<! - ko with:currentUser - >

'然後你可以使用'$ parents [1] .openProfile '在這兩種情況下。 – nemesv 2013-02-13 13:08:21

回答

3

我的Repeat綁定執行類似於foreach的操作,但不創建子上下文。

<div data-bind="repeat:users" 
    data-repeat-bind="template:{name:'userAvatar',data:$item()}"></div> 

適用於您的例子,因爲它使用template另一種選擇(也許更好),是foreach optiontemplate的:

<div data-bind="template:{name:'userAvater',foreach:users}"></div> 
+0

非常感謝,這就是我要找的。 – Kasheftin 2013-02-14 06:54:47

+0

我剛剛意識到有一個更好的解決方案,我已將其添加到我的答案中。 – 2013-02-14 09:32:53

0

您可以將用戶數組轉換爲對象並在該對象中實施點擊操作。

function User(name,avatarUrl) { 
    var self = this; 

    this.name = ko.observable(name); 
    this.avatarUrl = ko.observable(avatarUrl); 

    this.openProfile = function() { 
     .... 
    } 
} 


users = ko.observableArray([new User(...),new User(...)]); 

我認爲這個行爲自然屬於用戶模型而不是你的根模型。

相關問題