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

jsfiddle example with initial value for this.selectedSection. #18

Closed vdlindk closed 11 years ago

vdlindk commented 11 years ago

hello,

about a week ago I came across the knockout-amd-helpers and the knockout-postbox. I love the example in this post (http://jsfiddle.net/rniemeyer/mg3hj/)

I want to use this example to implement all navigations in my webapp. The example provided in jsfiddle is a very good starting point. Only I have one additional requirement: I want to provide an initial value to the observable that is published.

I tried the following code adaptations in 'http://jsfiddle.net/rniemeyer/mg3hj/'

var MenuModel = function() { this.name = ko.observable().subscribeTo("nickName"); this.sections = ["Profile", "Notifications"]; this.selectedSection = ko.observable().publishOn("section"); this.selectedSection(this.sections[0]); };

var MenuModel = function() { this.name = ko.observable().subscribeTo("nickName"); this.sections = ["Profile", "Notifications"]; this.selectedSection = ko.observable(this.sections[0]).publishOn("section"); };

For some reason the 'Profile' isn't selected automatically. My lack of knowledge will be probably the cause why this isn't working, so I was wondering: has somebody already tried this? if so... how does it to work?

thanks in advance,

Koen

rniemeyer commented 11 years ago

Looks like you are pretty close. One thing that you can do is add a "true" as the second argument to profile's subscribeTo call. This will populate it with the latest published value, so you don't have to worry about the order that things are created. It would look like:

    //apply a filter to turn the value that we receive into a boolean
    this.visible = ko.observable().subscribeTo("section", true, function(newValue) {
        return newValue === "Profile";
    });

Here is an updated fiddle: http://jsfiddle.net/rniemeyer/KBYna/

Hope that helps.

vdlindk commented 11 years ago

brilliant!

and most of all: a BIG thank you!