2015-08-17 82 views
0

这是我的代码:淘汰赛计算不点火订阅

self.convertedPrice = ko.computed(function() { 
    console.debug('Calculating convertedPrice'); 
    if (self.ProductListPrice() != null && self.multiplicationFactor() != null) { 
     return self.ProductListPrice() * self.multiplicationFactor(); 
    } 

    return 0; 
}).extend({notify:'always'}); 

self.convertedPrice.subscribe(function (newVal) { 
    console.debug('convertedPrice subscription fired.'); 
    self.discountedPrice(parseFloat(newVal).toFixed(2)); 
}); 

self.ProductListPrice更新,self.convertedPrice正确地更新和调试第一写入,但认购不烧成,第二调试语句不会被写入和self.discountedPrice未更新。

我已经通过将订阅的内容移动到计算的代码中来解决这个问题,但我想了解原始订阅无法工作的原因。如果我手动更改self.ProductListPriceself.multiplicationFactor,订阅就会触发,但是当它们因我的其他代码和用户输入而更改时,订阅不会触发。

任何想法我做错了什么?

+0

如果你想订阅计算何时启计算稍稍柚木它计算。使用'deferEvaluation:true' sample here http://jsfiddle.net/LkqTU/26144/ –

+0

我已经尝试推迟评估,同时试图自己跟踪这个,但它没有任何区别。谢谢你的想法。 – Tim

回答

2

我唯一的猜测是你在做一个赋值而不是在设置一个值时调用observables。下面的代码按预期工作。

function viewModel() { 
 
    var self = { 
 
    discountedPrice: ko.observable(), 
 
    ProductListPrice: ko.observable(), 
 
    multiplicationFactor: ko.observable() 
 
    }; 
 
    self.convertedPrice = ko.computed(function() { 
 
    console.debug('Calculating convertedPrice'); 
 
    if (self.ProductListPrice() != null && self.multiplicationFactor() != null) { 
 
     return self.ProductListPrice() * self.multiplicationFactor(); 
 
    } 
 

 
    return 0; 
 
    }).extend({ 
 
    notify: 'always' 
 
    }); 
 

 
    self.convertedPrice.subscribe(function(newVal) { 
 
    console.debug('convertedPrice subscription fired.'); 
 
    self.discountedPrice(parseFloat(newVal).toFixed(2)); 
 
    }); 
 
    return self; 
 
} 
 

 
ko.applyBindings(viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 
<div><label>List Price</label><input data-bind="value:ProductListPrice" /></div> 
 
<div><label>Multiplier</label><input data-bind="value:multiplicationFactor" /></div> 
 
<div><label>Converted</label> <span data-bind="text:convertedPrice"></span></div> 
 
<div><label>Discounted</label> <span data-bind="text:discountedPrice"></span></div>

+0

当你说做一个任务时,你的意思是使用(例如)'self.multiplicationFactor = 3;'而不是'self.multiplicationFactor(3);'?我知道这没有发生,因为变量都是可观察的,但不知道我是否误解了你的意思。 – Tim

+1

@Tim你理解正确。也可能(尽管不太可能)你正在做'self.multiplicationFactor = ko.observable(3)'这样的事情,这会让它成为一个可观察的事物,但是却是一个不同的,不受约束的事物。我只能说这里包含的代码没有问题。 –

+0

这是一个公平的评论,我会检查我没有做过这样愚蠢的事情。 – Tim