1

I'm playing around with Knockout and now trying to use the Knockout address plugin (based on jQuery address).

This code below works, except that when I try entering the address the linkObservableToUrl provides the page is loaded without the right tags. I guess something is wrong in the way I'm loading the messages, but I'm not sure how this should be done using the Knockout framework.

I've got the following code, which is causing an infinite loop:

var viewModel = {
    page: ko.observable(1),
    //messages: ko.observableArray([]),
    tags: ko.observable()
};

viewModel.filterTags = function (filterTags) {
    viewModel.tags(filterTags);
};

viewModel.messages = ko.dependentObservable(function () {
    $.ajax(
        // abbreviated
        data: ko.toJSON(viewModel),
        // abbreviated
)}, viewModel);

ko.applyBindings(viewModel);

ko.linkObservableToUrl(viewModel.tags, "tags", null);

How can I solve this and still have the messages depend on page and tags?

Jeroen
  • 60,696
  • 40
  • 206
  • 339
CD..
  • 72,281
  • 25
  • 154
  • 163

2 Answers2

3

Switch to AngularJS. Angular's databinding is much better than Knockout's. Much of the problems you are encountering here with infinite loops, etc. are due to Knockout's need for observable wrappers.

Angular does not require observable wrappers of your objects. Angular can observe any standard JSON/Javascript object, and databind directly to any HTML element via MVVM.

In Angular, you would simply make your AJAX call for ViewModel.messages, and the standard JSON would be applied to your ViewModel.messages property. No observable wrappers. This eliminates the need for ko.dependentObservable() and thus - removes your infinite loop.

http://www.angularjs.org

Ryan D. Hatch
  • 213
  • 2
  • 3
1

In the second example (which is quit long for a code snippet) you have this:

viewModel.messages = ko.dependentObservable(function () {
...
        data: ko.toJSON(viewModel),
...

If the call to ko.toJSON tries to get the value of all the observable properties on the view model, it will try to evaluate the viewModel.messages property. That will call ko.toJSON again, leading to an infinite loop.

Douglas
  • 36,802
  • 9
  • 76
  • 89
  • 10x, is their a simple way to get a JSON of all observable properties except the messages property? – CD.. Aug 29 '11 at 05:12
  • I don't know of a neat way to do that. You could split up the view model into a section that gets sent to the server and a section which doesn't, but my preference would be to explicitly pull out the properties that you want from the view model when you make the ajax request. It seems likely that you would add more things to the view model in the future which you wouldn't need to send to the server. (ie, follow the data transfer object (DTO) pattern, instead of trying to sent the whole view model) – Douglas Aug 29 '11 at 12:45