我刚刚开始使用knockout.js并且我的成绩很好,但我有一个小问题:
我有一个JSON列表,我用它来构建我的模板:
以下是制定清单的清单和代码:
public IEnumerable<dynamic> TheaterList { get; set; }
List<TheaterTest> theaters = new List<TheaterTest>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
getTheaters();
TheaterList = theaters;
}
}
protected void getTheaters()
{
theaters.Add(new TheaterTest()
{
theater_dist = "3",
theater_name = "Regal Webster Place 11",
theater_add1 = "1471 W. Webster Ave",
theater_add2 = "",
theater_city = "Chicago",
theater_state = "Il",
theater_postcode = "60614",
theater_phone = "(762) 711-9180"
});
theaters.Add(new TheaterTest()
{
theater_dist = "4.2",
theater_name = "Regal Washington Park 9",
theater_add1 = "1341 W Webster Ave",
theater_add2 = "",
theater_city = "Chicago",
theater_state = "Il",
theater_postcode = "60614",
theater_phone = "(762) 711-9180"
});
这是在.ascx
中构建JSON的代码<script>
var d = {};
d.theaterList = <%= Newtonsoft.Json.JsonConvert.SerializeObject(TheaterList) %> ;
$(document).ready(function () {
ko.applyBindings(new theaterSel.TheaterModel(d.theaterList));
});
</script>
这是我的模板:
<div class="theatre-info">
<div class="theater-name">
<a data-bind="attr: { href: ''}"><span class="theater-link" data-bind=" text: theater_name" /></a>
</div>
<div class="theatre-address" data-bind="text: theater_add1, text: theater_add2"></div>
<div class="theatre-address" data-bind="text: theater_city + text: theater_state + text: theater_postcode"></div>
<div class="theatre-phone" data-bind="text: theater_phone"></div>
<button>My Theatre</button>
</div>
</li>
我想连接theater_city,theater_state和theater_postcode:我想我可以使用“ko.compute ...但我不确定如何创建该功能。 任何帮助将不胜感激。
提前谢谢。
答案 0 :(得分:2)
是的,你走在正确的轨道上 -
在您的视图模型中
var computedName = ko.computed(function () {
return theater_city + ', ' + theater_state + ', ' + theater_postcode;
});
并在您的视图中
<h1 data-bind="text: computedName"></h1>