是否可以在不改變上下文的情況下使用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個級別。
這是一個例子,在這裏我可以用$根,但在真實情況我有多個嵌套模型,所以我的$ root很遠,它甚至不知道當前的模型及其方法。 – Kasheftin 2013-02-13 13:00:28
我知道這是一個黑客,但你可以在當前用戶tempalte周圍使用'with' ...'<! - ko with:currentUser - >
'然後你可以使用'$ parents [1] .openProfile '在這兩種情況下。 – nemesv 2013-02-13 13:08:21