(二)Knockout - ViewModel 的使用

 

计算属性

实际应用中,我们通常需要对数据进行加工

如: 指定日期格式,将数字相加... 等,此时可使用ko.computed()。当数据发生改变是,KO会使用computed重新计算

DEMO1

更改firstName,lastName值后改变fullName

 var AppViewModel = function() {
var me = this; me.firstName = ko.observable('Bob'); me.lastName = ko.observable('Smith'); me.fullName = ko.computed(function () { return me.firstName() + " " + me.lastName(); }, this); } ko.applyBindings(new AppViewModel());

绑定到View上

<p>First name: <input data-bind="value: firstName"/></p>

<p>Last name: <input data-bind="value: lastName"/></p>

<h2>Hello,   <span data-bind="text: fullName"/>!</h2>

 

DEMO2

修改fullName,从而更新firstName,lastName的值

<p>First name: <input data-bind="value: firstName"/></p>

<p>Last name: <input data-bind="value: lastName"/></p>

<h2>Hello,   <span data-bind="value: fullName"/>!</h2>
self.fullName = ko.computed({

    read: function () {

        return me.firstName() + " " + me.lastName();

    },

    write: function (value) {

        var lastSpacePos = value.lastIndexOf(" ");

        if (lastSpacePos > 0) { // Ignore values with no space character

            me.firstName(value.substring(0, lastSpacePos)); // Update "firstName"

            me.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"

        }

    },

    owner: me

});

 

DEMO3

金额格式的自动转换(包括精度和格式)已经垃圾字符的过滤

<p>Enter bid price: <input data-bind="value: formattedPrice"/></p><br/>
var parseModel = function() {

    var me = this;

    me .price = ko.observable(25.99);

    me .formattedPrice = ko.computed({

        read: function() {

            return '$' + me.price().toFixed(2);    

        },

        write: function(val) {

            val = parseFloat(value.replace(/[^\.\d]/g, ""));

            me.price(isNaN(val ) ? 0 : val ); 

        },

        owner: me

    });

      

};

ko.applyBindings(new parseModel());

 

DEMO4

过滤并验证用户输入

<p>Enter a numeric value: <input data-bind="value: attemptedValue"/>

    <span data-bind="visible:lastInputWasValid()">验证通过</span>

</p>
var MyViewModel = function() {

    var me = this;

    me.acceptedNumericValue = ko.observable(123);

    me.lastInputWasValid = ko.observable(true);



    me.attemptedValue = ko.computed({

        read: me.acceptedNumericValue,

        write: function (value) {

            if (isNaN(value))

                me.lastInputWasValid(false);

            else {

                me.lastInputWasValid(true);

                me.acceptedNumericValue(value); // Write to underlying storage

            }

        },

        owner: me

    });

}



ko.applyBindings(new MyViewModel());

 

你可能感兴趣的:(knockout)