here is what I need to accomplish in short: ‘dynamically change the style, based on computed value change’
I have an observable array with initial set of,let say, 3.
I do use a template with each element from the array going into a separate div (I float them to the left in css)
<script type="text/html" id="feedsTemplate">
<div style="float:left;" data-bind="style: { width: $root.CurrentColumnWidth()+'px'}">
<strong data-bind="text: SearchTerm"></strong>
</div>
</script>
here is my viewModel:
var viewModel = {
Feeds: ko.observableArray([
new Feed("Boston"),
new Feed("NewYork"),
new Feed("Chicago", ),
]),
GetLatestFeeds: function () { getLatestFeeds(); },
FeedsCounter: ko.observable(3),
CurrentColumnWidth: ko.computed (function()
{
return ((GetCurrentPageWidth() / this.FeedsCounter));
},this)
};
depending on the number of elements in that array, I calculate the width of the div where each of the element will be placed.
(I tried not to use the counter and refer directly to the viewModel.Feeds.length, but it seems there is no length in observableArray)
The problem I have is that after the number of elements in Feeds increased, due to the updates from the server, there is no recalculation happens for the div width.
here is update function:
function getLatestFeeds()
{
$.getJSON('/Feed/GetUpdatedFeeds', function (data)
{
$.each(data, function ()
{
viewModel.Feeds.push(new Feed(this.SearchTerm, this.FeedItems));
viewModel.FeedsCounter = viewModel.FeedsCounter + 1;
});
});
}
as far as I understand, from http://www.knockoutjs.com:
“… and they will be updated whenever firstName or lastName changes (your evaluator function will be called once each time any of its dependencies change, and whatever value you return will be passed on to the observers such as UI elements or other computed observables).”
whenever FeedsCounter changes, the computed var is updated too, and as I have it bounded to the div’s css, with width should change as well.. That just does not happen.
will appreciate any help/suggestions/pointers.
Thanks!
When you get value from observable you should use
()because it is a function. The same for setting values: