Domanda

In my Knockout/Sammy SPA, I would like to access ViewModel data in my Sammy route, however, the Sammy route is executed before my Knockout behavior. It works on the initial route because I'm setting self.selectedPage() equal to the first page, but it doesn't work for subsequent routes...

function MyViewModel() {
    var self = this;

    self.pages = [
        {'linkText': 'Home', 'pageTitle': 'Welcome', 'route': '#/'},
        {'linkText': 'About', 'pageTitle': 'About Us', 'route': '#/about'},
    ]

    self.selectedPage = ko.observable(self.pages[0]);

    self.goToPage = function(page) {
        self.selectedPage(page);
    }

    Sammy(function() {
        this.use(Sammy.Title);
        this.setTitle('The Base Title');

        this.get('#/', function(context) {
            this.title(self.selectedPage().title); //works
        });

        this.get('#/about', function(context) {
            this.title(self.selectedPage().title); //title is undefined
        });
    }).run('#/');
}

ko.applyBindings(new MyViewModel());

I have also tried retrieving the page from the array based on the route property of the page and setting self.selectedPage() in the Sammy route, which will correctly set the selectedPage observable to the right page within the scope of the route event, but when I try to access a property of that view model, like: self.selectedPage().title, I get back undefined, which is odd, because console.log(self.selectedPage()) will show the property.

Can someone please point out what I'm doing wrong?

È stato utile?

Soluzione

The way your page object is defined, it doesn't have a title property, but a pageTitle. Have you tried

this.get('#/about', function(context) {
        this.title(self.selectedPage().pageTitle); 
    });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top