Search code examples
javascriptmvvmknockout.jsknockout-3.0

Thought I understood Knockout.js, now I'm not so sure


Pretty unsure if I used to understand and now do not understand it, or if I didn't understand it and now I'm starting to... or if I didn't and still don't.

I'm building an app that lets users book appointments.

Screen 1: Select a Location and Service Type (Options lists, button to confirm and move on)

Screen 2: Select an available Appointment time (table, button to confirm and move on)

Screen 3: Enter Name and Contact Info (text inputs, button to confirm and move on)

Screen 4: Enter verification code (texted to user, button to confirm and move on)

Screen 5: Displays confirmation code

I'm refactoring because I realized everything was in my ViewModel and unsure of what belongs in my Model and what belongs in my ViewModel. I just put selectedLocation (the item the user picks from the list) in the Model but I need it to be accessible by the View, so I did this:

self.selectedLocation = ko.pureComputed({
    read: function() {
        return self.model.selectedLocation();
    },
    write: function(value){
        self.model.selectedLocation(value);
    }
});

Which just seems bonkers.

Should this just be in the ViewModel? Should I have a selectedLocation variable in the Model and a currentlySelectedLocation in the ViewModel that then updates model.selectedLocation when the user confirms the Location and Service Type?

Should each separate screen have it's own viewmodel? I'm using a single .html file and updating what is displayed rather than going from page to page.

I'm sure I'm not including some kind of vital piece of information and I apologize, happy to answer any questions.

Any help would be greatly appreciated.


Solution

  • The cool thing about observables is that you can just use them in other objects:

    self.selectedLocation = self.model.selectedLocation;
    

    But I would suggest that it's also fine to just bind directly to model.selectedLocation. In Knockout, there's no need to have a model/view-model distinction; everything is a view-model.