当用户修改或编辑jqxGrid中的行时,如何防止在observableArray中更改对象的这种行为。 我有一个淘汰可观察的用户数组,其中每个用户都将属性作为可观察对象,然后我将该可观察数组绑定到jqxGrid(来自jqWidgets)。当我在网格中更新User值时,然后在可观察数组中该项被替换为包含此User的observable值的对象。
以下是我的代码:
HTML部分:
<div class="container">
<div id="jqxGrid"
data-bind="jqxGrid: {
source: Users,
editable: true,
width: '100%',
selectionmode: 'singlecell',
columns: [
{ text: 'IsChecked', columntype: 'checkbox', dataField: 'IsChecked', width: '10%' },
{ text: 'FirstName', dataField: 'FirstName', width: '40%', editable: false, sortable: true },
{ text: 'LastName', dataField: 'LastName', width: '40%', editable: true, sortable: true }
]
}">
</div>
</div>
Javascript代码:(创建Users数组,ViewModel初始化,ko.applyBindings调用。)
function UserModel (user) {
var self = this;
self.IsChecked = ko.observable(false); // later I will use this proerty in other place
self.Username = ko.observable(user.Username);
self.FirstName = ko.observable(user.FirstName);
self.LastName = ko.observable(user.LastName);
// I want to put a isDirty property here
}
var initialUsers = [
new UserModel({ Username: 'JohnMicrosoft', FirstName: 'John', LastName: 'Microsoft' }),
new UserModel({ Username: 'JohnGoogle', FirstName: 'John', LastName: 'Google' }),
new UserModel({ Username: 'JohnApple', FirstName: 'John', LastName: 'Apple' }),
];
var viewModel = null;
$(document).ready(function () {
viewModel = new UserViewModel(initialUsers);
ko.applyBindings(viewModel);
});
function UserViewModel(initialUsers) {
var self = this;
self.Users = ko.observableArray(initialUsers);
};
此图像显示在我单击IsChecked复选框的第一行后值如何变化。
点击jqxGrid中第一行的IsChecked checbox的结果
问题是我想向UserModel对象添加一些函数,我想保留observable,因为我想在页面的其他部分使用它们。我已经在这工作了几天,不知道该怎么做任何帮助将不胜感激。感谢。
答案 0 :(得分:0)
我做了类似的事情。也许它可以帮到你:
var Goods = function (obj) {
var name = ko.observable(obj.name);
var sales = ko.observable(obj.sales);
var price = ko.observable(obj.price);
var extra = ko.observable(obj.extra);
var id = ko.observable(obj.id);
name.subscribe(alert('name changed'));
return {
name: name,
sales: sales,
price: price,
extra: extra,
id: id
};
};
var items = ko.observableArray([
new Goods({ id: 1, name: "Furious Lizard", sales: 152, price: 25.00 }),
new Goods({ id: 2, name: "Indifferent Monkey", sales: 1, price: 99.95 }),
]);
var source = {
localdata: items,
datatype: 'local'
};
在视图中我只有这个:
<div id="jqxgrid"></div>
在文档就绪功能中,我已经初始化了网格:
$("#jqxgrid").jqxGrid({
source: source,
....
});