knockout 简单使用

Posted 欣欣点灯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了knockout 简单使用相关的知识,希望对你有一定的参考价值。

定义:

    var QcViewModel = function () {
        var self = this;
        self.name = ko.observable();
        self.qty = ko.observable();
    };

     var RecordviewModel =function() {
        var self = this;
        self.temperature = ko.observable(80);
        self.prodname = ko.observable(D成型);
        self.typename = ko.observable(L);
        self.ftargetqty = ko.observable(1000);
        self.prodqty = ko.observable(500);
        self.rate = ko.observable(50);
        self.rateless = ko.observable(50);

        self.Detail1 = ko.observableArray([new QcViewModel()]);
        self.Detail2 = ko.observableArray([new QcViewModel()]);
        self.Detail3 = ko.observableArray([new QcViewModel()]);
    };

     var myViewModel = new RecordviewModel();

初始化:

ko.applyBindings(myViewModel);

修改值:

myViewModel.temperature(data.temperature);

var mapping = {
    ‘Detail1‘: {
        create: function (options) {
            var newItem = new QcViewModel();
            newItem.name(options.name);
            newItem.qty(options.qty);
            return newItem;
        }
    }, ‘Detail2‘: {
        create: function (options) {
            var newItem = new QcViewModel();
            newItem.name(options.name);
            newItem.qty(options.qty);
            return newItem;
        }
    }, ‘Detail3‘: {
        create: function (options) {
            console.log(‘Detail3:=‘+options);
            var newItem = new QcViewModel();
            newItem.name(options.name);
            newItem.qty(options.qty);
            return newItem;
        }
    }
};
ko.mapping.fromJS(Detail1, mapping, myViewModel.Detail1);
ko.mapping.fromJS(Detail2, mapping, myViewModel.Detail2);
ko.mapping.fromJS(Detail3, mapping, myViewModel.Detail3);

绑定:

<span data-bind="text: temperature"></span>

遍历:

<div class="col-sm-6 col-md-6" data-bind="foreach: Detail1()">
    <h2> <span style="color:red" data-bind="text: qty">90</span> <span style="color:greenyellow" data-bind="text: name"></span></h2>
</div>

 

以上是关于knockout 简单使用的主要内容,如果未能解决你的问题,请参考以下文章

如何在 TypeScript 中导入 KnockOut 4?

knockout 简单使用

knockout 学习使用笔记----绑定map--双向绑定

knockout获取datepicker的时间

Knockout.js简介

Knockout.js 数据验证之插件版和无插件版