首页 > 代码库 > knockout 简单使用

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 简单使用