动态的列和行与基因剔除 [英] dynamic column and rows with knockoutjs

查看:79
本文介绍了动态的列和行与基因剔除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面代码中的输入参数只是一个表名,

My input parameter for the code below is just a tablename,

我能够查询json格式的数据返回, 但是,我无法显示我的行数据项. 知道我做错了什么吗?

I was able to query the data return in json format, however, i am not able to display my rows item of data. any idea what did i do wrong?

<script>
var invtype = "@ViewBag.invtype";

    function ViewModel() {  

        var self = this;
        function ColName(tbstruct){ 
            this.ColumnName = tbstruct.ColumnName
        }

        self.TBStruct = ko.observableArray(); 
        self.items = ko.observableArray(); 

        self.invtype = invtype;

        self.Load = function () {


    //expected data for self.items
    //[{"$id":"1","Id":2,"Inv_Id":"PV0001-1","ACX_No":"6","ACX_Name":"ABC","S_No":"5", "Acc_Class":"Local","Direction":"Two-Way"},{"$id":"2","Id":2,"Inv_Id":"PV0002-1","ACX_No":"3","ACX_Name":"CKD","S_No":"6", "Acc_Class":"Local","Direction":"Two-Way"}]


            $.ajax({
                    url: "@Url.Content("~/api/")"+self.invtype, 
                    type: 'GET',
                    dataType: 'JSON',
                    success: function (data) {
                        // Map the returned JSON to the View Model  

                        self.items = data;
                    }
            });

//expected data
     //[{"$id":"1","ColumnName":"Id","system_type_id":56,"primaryCol":1}, {"$id":"2","ColumnName":"Inv_Id","system_type_id":231,"primaryCol":0},{"$id":"3","ColumnName":"ACX_No","system_type_id":175,"primaryCol":0},{"$id":"4","ColumnName":"ACX_Name","system_type_id":175,"primaryCol":0},{"$id":"5","ColumnName":"S_No","system_type_id":175,"primaryCol":0} {"$id":"27","ColumnName":"Acc_Class","system_type_id":231,"primaryCol":0},{"$id":"28","ColumnName":"Direction","system_type_id":231,"primaryCol":0} ]

            $.ajax({
                    url: "@Url.Content("~/api/inventories/")"+self.invtype,
                    type: 'GET',
                    dataType: 'JSON',
                    success: function (data) {
                        // Map the returned JSON to the View Model  
                        $.each(data,function(i,dt){
                            //console.log(dt.ColumnName);
                            self.TBStruct.push(new ColName(dt));
                        });
                        //console.dir(self.TBStruct);
                    }
            });
            return self;
        };
    } 

    var View = new ViewModel();
    ko.applyBindings(View.Load()); 

在这里我试图将它们显示出来.

here i am trying to display them out.

    <thead>
        <tr data-bind="foreach: TBStruct">
            <th data-bind="text: ColumnName"></th>
        </tr>
    </thead>

    <tbody >
        <tr data-bind="foreach: items" >
            <td data-bind="text:$data"></td> 
        </tr> 
    </tbody>
</table>

推荐答案

function ViewModel() {
    var self = this;

    self.invtype = "@ViewBag.invtype";
    self.columns = ko.observableArray();
    self.rows = ko.observableArray();

    self.load = function () {
        $.when(
            $.get("@Url.Content('~/api/inventories/')" + self.invtype),
            $.get("@Url.Content('~/api/')" + self.invtype)
        )
        .then(function (columnResponse, rowResponse) {
            var columnDefs = columnResponse[0],
                rowDefs = rowResponse[0],
                columnMapping = {
                    key: function (data) {
                        return ko.utils.unwrapObservable(data.ColumnName);
                    }
                },
                rowMapping = {
                    key: function (data) {
                        return ko.utils.unwrapObservable(data.Id);
                    }
                };

            ko.mapping.fromJS(columnDefs, columnMapping, self.columns);
            ko.mapping.fromJS(rowDefs, rowMapping, self.rows);
        });

        return self;
    };
}

注意:

  • 使用jQuery的.when().then()确保仅在两个HTML请求都成功返回之后才进行视图模型处理.请参阅有关该主题的jQuery文档.
  • 自定义映射中的key函数可确保再次调用load()时,仅视图模型的适当部分得到更新.否则,ko.mapping.fromJS将替换整个可观察的部分,从而完全重建页面的受影响部分.指定key允许部分页面更新,因此请在此处使用数据的唯一属性. (如果您不打算在页面生命周期内从服务器刷新数据,则可能不需要此步骤.)
  • 必须使用ko.utils.unwrapObservable(),因为在加载操作期间,key将同时用于现有视图模型内容服务器响应,因此例如data.ColumnName可能是可观察到的或原始值.
  • 请务必通读映射插件文档的高级部分,您可能会找到其他有用的地方.
  • Using jQuery's .when() and .then() ensures that view model processing occurs only after both HTML requests have returned successfully. See jQuery's documentation on the topic.
  • The key function in the custom mapping ensures that when you call load() again then only the appropriate parts of your view model get an update. Otherwise ko.mapping.fromJS will replace the entire observable, resulting in a complete re-build of the affected part of your page. Specifying key allows partial page updates, so use a unique property of your data here. (If you don't plan on refreshing data from the server during page life time this step might not be necessary.)
  • The use of ko.utils.unwrapObservable() is mandatory because during a load operation key will be used on both the existing view model contents and the server response, so for example data.ColumnName could be an observable or a raw value.
  • Be sure to read through the advanced section of the mapping plugin documentation, you might find other helpful bits.

HTML

<table>
    <thead>
        <tr data-bind="foreach: $root.columns">
            <th data-bind="text: ColumnName"></th>
        </tr>
    </thead>
    <tbody data-bind="foreach: $root.rows">
        <tr data-bind="foreach: $root.columns">
            <td data-bind="text: $parent[ColumnName()]"></td>
        </tr>
    </tbody>
</table>

注意:

  • 实际上唯一需要$root的地方是在<tr data-bind="foreach: $root.columns">绑定中.其他的只是为了保持一致性.
  • $parent引用foreach: $root.rows中的行.
  • $parent[ColumnName()]中的括号是必需的,因为ColumnName是可观察的,并且在复杂的绑定中,它们不会自动展开.
  • The only place where $root is actually necessary is in the <tr data-bind="foreach: $root.columns"> binding. The others are just included for consistency.
  • $parent refers to the row from foreach: $root.rows.
  • The parentheses in $parent[ColumnName()] are necessary because ColumnName is an observable and in a complex binding they are not unwrapped automatically.

整个内容可以在这里看到: http://jsfiddle.net/Tomalak/A6T8p/
此处(扩展版本): http://jsfiddle.net/Tomalak/A6T8p/1

The whole thing can be seen here: http://jsfiddle.net/Tomalak/A6T8p/
and here (extended version): http://jsfiddle.net/Tomalak/A6T8p/1

这篇关于动态的列和行与基因剔除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆