Disabling subscribers for knockouts for the model and re-enabling

I'm new to knockout and don't know if I'm doing it right or not.

I have a shopping cart editor, just like knockout examples, except that I want to have a more advanced selector . my products really have two codes, which the user should be able to enter one of them and get full information about the product on his cart. so I will have two inputs for each type of code, and when the user enters the code in any of them, I have to make an ajax call and download the product information (including productId, productName, the_other_code, etc.).

I'v tried to do this by subscribing to code1 and code2 - to make an ajax call and set the model data after receiving data from the server, but it makes a kind of recursive event (subscription) and, thus, calls ajax methods again. thus, I believe that if you can disable the knockout subscription during the SetData method, then the recursive act will not happen.

 function Product(data) { var self = this; self.ProductId = ko.observable(); self.Code1 = ko.observable(); self.Code2 = ko.observable(); self.Title = ko.observable(); self.SetData = function (itemdata) { self.ProductId (itemdata ? itemdata.ProductId : null); self.Code1(itemdata ? itemdata.Code1 : null); self.Code2(itemdata ? itemdata.Code2 : null); self.Title(itemdata ? itemdata.Title : null); }; self.SetData(data); self.Code1.subscribe(function (value) { var productInfo = Ajax_GetPartDataWithCode1(value); self.SetData(productInfo ); }); self.Code2.subscribe(function (value) { var productInfo = Ajax_GetPartDataWithCode2(value); self.SetData(productInfo ); }); } 

any help would be very convenient!

+4
source share
1 answer

A simple boolean flag is enough. Set true when entering SetData and false when exiting it, and then immediately return in the subscription callback if the flag is set:

  var updatingData = false; self.SetData = function (itemdata) { updatingData = true; self.ProductId (itemdata ? itemdata.ProductId : null); self.Code1(itemdata ? itemdata.Code1 : null); self.Code2(itemdata ? itemdata.Code2 : null); self.Title(itemdata ? itemdata.Title : null); updatingData = false; }; self.SetData(data); self.Code1.subscribe(function (value) { if (updatingData) return; var productInfo = Ajax_GetPartDataWithCode1(value); self.SetData(productInfo); }); self.Code2.subscribe(function (value) { if (updatingData) return; var productInfo = Ajax_GetPartDataWithCode2(value); self.SetData(productInfo); }); 
+2
source

All Articles