2013-02-05 137 views
3

有沒有辦法向WinJS.Binding.converter()函數發送多個參數?請看下面的數據和輸出:發送多個參數到WinJS.Binding.converter()函數

 { contactName: "Tara Miller", mainNumber: "555-405-6190", alternateNumber: "555-209-1927" }, 
     { contactName: "Bryan Bond",        alternateNumber: "555-574-4270" }, 
     { contactName: "Jenna Siever", mainNumber: "555-843-8823", alternateNumber: "555-799-5424" }, 

enter image description here

下面是HTML。該MyData.chooseBestNumber轉換器的功能是用來顯示無論是一個人的主要電話號碼或將「無主號」,如果他們沒有一個主號:

<div id="listViewTemplate" data-win-control="WinJS.Binding.Template"> 
    <div class="contactCard"> 
     <div data-win-bind="innerText: contactName"></div> 
     <div data-win-bind="innerText: mainNumber MyData.chooseBestNumber"></div> 
    </div> 
</div> 

這裏是JS定義轉換器功能:

WinJS.Namespace.define("MyData", { 
    chooseBestNumber: WinJS.Binding.converter(function (mainNumber) { 
     if (mainNumber) return mainNumber; 
     else return "no main number"; 
    }), 
}); 

下面是我最終希望能夠做到的......將多個參數傳遞到轉換函數,以便我可以返回主數字(如果已定義),備用數字(作爲後備)或消息(如果一切都失敗):

WinJS.Namespace.define("MyData", { 
    chooseBestNumber: WinJS.Binding.converter(function (mainNumber, alternateNumber) { 
     if (mainNumber) return mainNumber; 
     else if (alternateNumber) return alternateNumber; 
     else return "no phone numbers"; 
    }), 
}); 

是否可以向WinJS.Binding.converter()函數發送多個參數?

回答

7

實際上,您可以將您的電話號碼div綁定到this關鍵字,這將有效地將該div的innerText屬性綁定到整個模型對象。這樣在你的轉換器中,你可以訪問整個模型。

所以你更新的代碼應該是這樣的:

HTML

<div id="listViewTemplate" data-win-control="WinJS.Binding.Template"> 
    <div class="contactCard"> 
     <div data-win-bind="innerText: contactName"></div> 
     <div data-win-bind="innerText: this MyData.chooseBestNumber"></div> 
    </div> 
</div> 

JavaScript的轉換器

WinJS.Namespace.define("MyData", { 
    chooseBestNumber: WinJS.Binding.converter(function (model) { 
     if (model && model.mainNumber) return mainNumber; 
     else if (model && model.alternateNumber) return alternateNumber; 
     else return "no main number"; 
    }), 
});