rniemeyer / knockout-postbox

A small library that uses Knockout's native pub/sub capabilities to facilitate decoupled communication between separate view models or components.
MIT License
348 stars 55 forks source link

How can I implement async dependencies with knockout-postbox? #6

Closed fbuchinger closed 11 years ago

fbuchinger commented 12 years ago

I want to implement ajax-powered dependencies between knockout.observables (e.g. country -> province -> city selection) using postbox. When the user selects a country, an ajax request to a dependencyController should be issued, which in turn responds with values for the dependent province and cities fields.

How can I update the observable values in the publishOn/subscribeTo callbacks?

Here is my initial implementation:

 var CountryDependency = function() {
        var self = this;
        this.country = ko.observable("Austria").publishOn("country");
        this.province = ko.observable().subscribeTo("country", function(newValue){
            $.get('/dependencyController?country=' + self.country(), function(response){
               //how can i update province with the value from the server?
                newValue = response.province;
            });
        }).publishOn("province");
        this.cities = ko.observable().subscribeTo("province", function (newValue){
            //another ajax request to dependency controller here
        });
    };
rniemeyer commented 12 years ago

Hello- Here is a sample that uses manual subscriptions to update dependent dropdowns via AJAX requests: http://jsfiddle.net/rniemeyer/nj3ps/. Maybe you can take a look at that sample first and then we can discuss if you do need to involve postbox in the equation or not. Thanks!

fbuchinger commented 11 years ago

Hi Ryan,

thanks for the helpful example! Turns out I don't need postbox for the ajax updates.