更改列名称knockout simplegrid

时间:2013-08-07 08:37:51

标签: knockout.js

我能够将数据绑定到简单的网格,但是可以动态更改列名。列的名称将是用户在文本框中输入的内容。所以这是我的观点模型

var initialData = [{
name: "Well-Travelled Kitten",
sales: 352,
price: 75.95,
whatever: 10
 }, {
    name: "Speedy Coyote",
sales: 89,
price: 190.00,
whatever: 100
}, ];

function viewModel() {
var self = this;
self.queryResult = ko.observableArray();
this.update = function (data) {
    //this is an ajax call and return dateset back
    $.each(initialData, function (index, item) {
        self.queryResult.push(item);
    });


};

  self.gridViewModel = new ko.simpleGrid.viewModel({
   data: self.queryResult,
    columns: [
        { headerText: "Name", rowText: "name" },
        { headerText: "Sales ", rowText: "sales" },
        { headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
    ],
    pageSize: 4
});


 }

var PagedGridModel = function (items) {
    this.items = ko.observableArray(items);

    this.jumpToFirstPage = function () {
     this.gridViewModel.currentPageIndex(0);
};

};

  ko.applyBindings(new viewModel());

查看小提琴here

现在只是为了演示,可以将列名称设为“Well-Traveled Kitten” 而不是当前的硬编码列“名称”?

在我的真实场景中,用户将在文本框中输入一些文本,当我们加载网格时,列名称将更改为在文本框中输入的内容。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

是的,您可以从视图模型中将列名设置为可观察的。更新的小提琴:http://jsfiddle.net/DoctorMick/FB6LA/37/。主要变化是:

function viewModel() {
    var self = this;
    self.NameTitle = ko.observable("Some title");
    self.queryResult = ko.observableArray();
    this.update = function (data) {
        self.NameTitle(initialData[0].name); 
        //YOUR EXISTING CODE...
    }

    self.gridViewModel = new ko.simpleGrid.viewModel({
       data: self.queryResult,
        columns: [
            { headerText: self.NameTitle, rowText: "name" },
            { headerText: "Sales ", rowText: "sales" },
            { headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
        ],
        pageSize: 4
    });
}