Refresh data from server and coping with null data

69 views
Skip to first unread message

Steve Clements

unread,
Apr 23, 2012, 1:28:23 PM4/23/12
to KnockoutJS
HI,
This is my first project using knockout and i'm struggling with a
refreshing my data and applying bindings.

I'm getting the data from the server and using ko.mapping.fromJS to
load it into my view.

I don't have a viewModel defined, I like the easy of doing it like
this and the flexibility of letting the server control the model.

All the data is in an object property called Data (handy!).

Data contains (in this instance) several objects beneath it and some
beneath them. One is as array which I am binding with a foreach loop.

My problem is with refreshing the data using
ko.mapping.fromJS(jsonData, viewModel);

Outside of the foreach loop I am trying to just display some
properties - these may or may not be null.

I've tried using an if block, which seems to work - but only once...at
page load - when I refresh the data that doesn't seem to be checked.
So I looked at this... http://jsfiddle.net/rniemeyer/ShwP9/ and it
simply doesn't seem to work!

I also have a property call DataCount which will be zero if there is
no data. If this is zero I dont want to display my header section. I
also would prefer no to have to build the entire object model just to
satisfy knockout.

ko.observable.fn.trackComments = function () {
log("track");
this.hasComments = ko.observable();
this.subscribe(function (nv) {
log("change");
this.hasComments(nv && nv > 0 ? true : null);
log(nv && nv > 0 ? true : null);
log(nv);
}, this);
this.valueHasMutated();
return this;
};

// on load
.viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);

//on refresh
ko.mapping.fromJS(data, wikiComments.viewModel);

//always
viewModel.DataCount.trackComments();

// VIEW
<span id="stock_meta" class="stock-meta">
<!-- ko if: DataCount.hasComments -->
<!-- /ko -->
</span>

The logging in the JS does output true or false at the correct
time...however knockout would appear to have no idea what hasComments
is.

So I tried simply doing an if on one of the properties that will no be
there if its not bound.
<!-- ko if: Data.Changed1.Summary.Changed2.Count -->

that will hide when it doesnt exist - it doesn't however show when i
refresh the data and it does exist? So i added in this line (i'm not
sure I have the syntax correct...documentation is light).

ko.applyBindings(viewModel, $("#stock_meta")[0]);

but alas...that doesnt work either...

Seems to me there must be a better way of dealing with null values?

Would be nice if knockout could cope with the null value and simply
ignore it...not totally break the page and stop any other JS from
being executed.

What the best way to handle this situation?

Thx



Reply all
Reply to author
Forward
0 new messages