Knockout JS中的扩展器具有多个参数

时间:2014-05-29 10:51:32

标签: javascript knockout.js

可以在knockout.js中使用带有多个参数的extenders

示例:

ko.extenders.currency = function(target, currencySymbol, position) {
    var result = ko.computed({
        read: target,  
        write: function(newValue) {
            var current = target(),
            if (position == 'left') {
                target(currencySymbol+target);
            } else {
                target(target+currencySymbol);
            }
        }
    }).extend({ notify: 'always' });

但是我如何将它绑定到observable?

this.One = ko.observable(one).extend({ currency: ???, currencySymbol: '£', position : 'left'});

1 个答案:

答案 0 :(得分:12)

您需要使用一个对象,例如:

ko.extenders.currency = function(target, options) {
    var currencySymbol = options.symbol,
        position = options.position;
    var result = ko.computed({
        read: target,  
        write: function(newValue) {
            var current = target(),
            if (position == 'left') {
                target(currencySymbol+target);
            } else {
                target(target+currencySymbol);
            }
        }
    }).extend({ notify: 'always' });

然后,你会这样称呼它:

this.One = ko.observable(one).extend({ currency: { symbol: '£', position : 'left' } });

或者如果您更喜欢更易读的代码:

var currencyOptions = { symbol: '£', position: 'left' };
this.One = ko.observable(one).extend({ currency: currencyOptions });