我对 knockout.js 很陌生,但到目前为止我很喜欢它!我正在用 MVC4 编写并遇到了一些障碍。我已经用静态数据搞定了 kojs,但我现在使用的是通过 JSON 从控制器传递的数据,并且不确定如何执行此操作。
最初我的活动有一个“课程”:
function Activity(context) {
var self = this;
self.type = context.type;
self.name = context.name;
self.time = ko.observable(context.time);
self.product = context.product;
self.item = context.item;
self.itemAmount = context.itemAmount;
self.formattedPrice = ko.computed(function () {
var price = context.netPrice;
return price ? "$" + price.toFixed(2) : "None";
});
}
在我的视图模型中填充了静态数据:
self.activities = ko.observableArray([
new Activity({ type: 1, name: "John Smith", time: "1 hour", itemAmount: "5", netPrice: 232.16 }),
new Activity({ type: 1, name: "Jane Doe", time: "2 hours", itemAmount: "7", netPrice: 4812.30 }),
new Activity({ type: 1, name: "Clark Kent", time: "4 hours", itemAmount: "5", netPrice: 19.09 }),
]);
这很棒,我可以使用 ko.computed 方法来更改我的数据。现在我正在提取我的数据,我已经将我的代码压缩为:
function ActivityViewModel() {
var self = this;
self.activities = ko.observableArray();
$.getJSON("Home/ActivityData", self.activities);
}
效果很好,在我的数据绑定字段中,我只是将我的文本调用从它们的变量名转换为以 $data 开头的数据库记录名。-- 很酷很简单。
问题是我有一个时间字段,我需要通过 moment.js “人性化”,所以问题是......我如何访问 self.activities 后 JSON 数据并编辑特定字段?
抱歉,如果这很容易,但我没有运气在这件事上找到帮助(我可能没有找到正确的位置)。提前致谢!
更新
从服务器获取 JSON'd 的数据来自此 LINQ 查询:
var Data = from m in dataContext.Activities
select new
{
Type = m.Type,
ClientName = m.ClientName,
UserID = m.UserID,
ProductsNo = m.ProductsNo,
ProductName = m.ProductName,
NetPrice = m.NetPrice,
Time = System.Data.Linq.SqlClient.SqlMethods.DateDiffSecond(m.RecordCreated, DateTime.Now)
};
我需要在客户端做的是获取 Time 变量并在 javascript 中针对它运行一个函数。我假设它是用 ko.computed() 函数完成的,但是我似乎无法弄清楚一旦将 Time 变量拉入 self.activities 后如何定位它。