我正在与淘汰赛扩展器挣扎。当我使用返回计算的observable的文档中的示例时,只能在创建observable时附加扩展器,或者替换observable,我无法完全监视后果。
有没有办法创建一个具有相同功能的扩展器,除了创建observable之外还可以附加它?
//would like this to work
this.myNumberTwo = ko.observable(0);
//somewhere else
this.myNumberTwo.extend({ numeric: 0 });
答案 0 :(得分:0)
创建新的observable或computed是在值到达原始observable之前拦截它的唯一方法。如果这对您不重要,那么您可以尝试订阅扩展器内的原始可观察对象。这将允许原始observable更改,然后您可以通过使用舍入值第二次更新它来对新值执行操作。如果您对观察者有任何其他订阅,则每次更改都会收到两次通知。
indent = ""
def perm(n, i):
global indent
indent += " "
print indent, "ENTER", n, i
if i == len(n) - 1:
print n
else:
for j in range(i, len(n)):
print indent, "RECUR", i, j
n[i], n[j] = n[j], n[i]
perm(n, i + 1)
n[i], n[j] = n[j], n[i] # swap back, for the next loop
indent = indent[2:]
perm([1, 2, 3], 0)
答案 1 :(得分:0)
感觉它主要是语法问题,因为你已经弄清楚它应该如何工作。
如果您想要动态启用和关闭扩展程序,我建议使用此样式稍加改动dragEnterEvent()
扩展程序:
numeric
var myNumber = ko.observable(1.234).extend({ obsNumeric: null });
myNumber.setPrecision(0); // Gives you `1`
myNumber.setPrecision(null); // Gives you the original value

ko.extenders.obsNumeric = function(target, initialPrecision) {
var precision = ko.observable(initialPrecision);
// When reading, apply the precision
var computed = ko.pureComputed({
read: function() {
var prec = precision();
var val = target();
return prec || prec === 0
? numeric(prec,val)
: val;
},
write: target
});
// Expose the precision setting
computed.setPrecision = precision;
return computed;
}
var myNumber = ko.observable(1.2345678).extend({ obsNumeric: false });
// When passing null, NaN or false, no precision is applied
console.log(myNumber());
// We can change the precision without loosing our original value
myNumber.setPrecision(0);
console.log(myNumber());
// Which means we can even go up in precision without resulting in .000
myNumber.setPrecision(3);
console.log(myNumber());
function numeric(precision, nr) {
var roundingMultiplier = Math.pow(10, precision);
var newValueAsNum = isNaN(nr) ? 0 : +nr;
return Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
};