可以在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' });
但那我怎么把它绑定到可观察的?
this.One = ko.observable(one).extend({ currency: ???,currencySymbol: '£',position : 'left'});
解决方法
您需要使用一个对象,例如:
ko.extenders.currency = function(target,options) { var currencySymbol = options.symbol,position = options.position; var result = ko.computed({ read: 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 });