O.O
O.O

Reputation: 11307

How to update model property automatically from view model?

EDIT - adding more "realistic code" per comment. Design goal is that all models are wrapped by view models and the view model acts as a proxy to the model. The view never binds directly to a model. Also, I have a separate javascript class that sends and receives models to/from the server that is injected as a dependency into the view models.

Below, the MessageModel's content is the raw content the user typed and/or what the server returned. MessageViewModel exposes a message property which is a formatted version of the model's content property.

function MessageModel(id, content, nick) {
    var self = this;
    self.nick = nick;
    self.content = content;
    self.id = id;
}

// view needs to bind to properties that only exist on the view model
function MessageViewModel(messageModel, dataService) {
    var self = this;
    self.id = ko.observable(messageModel.id);
    self.message = ko.computed(function() {
        // format the content for the view
        return messageModel.nick + " <" + messageModel.content + ">";
    });
    self.saveMessage(function() {
        // send the model up to the server
        dataService.saveMessage(self.model);
    });
    self.model = messageModel;
}

With what I wrote above, changes to the view model need to be pushed to the model and when receiving models from the server, changes need to be pushed to be reflected in the view model and then to the view. How to do this in knockout?

Upvotes: 0

Views: 396

Answers (1)

Roy J
Roy J

Reputation: 43881

It is better to think of modeling the application rather than implementing a data model separately in your app code. The data model is on the server, isn't it? It's entirely redundant to copy values from your viewmodel to your data model within the app. Copy them to the server. But if you want to, you can subscribe to the observable and copy the value elsewhere.

See the docs on MVVM and ViewModels and note the distinction is between the "stored" data and the data in the app. The data is (usually) stored on a server. Once you've brought it into the app, it's viewmodel data. The interface between the viewmodel and the model is (usually) the ajax calls that load data to the app and save them back to the server.

The only thing you need to model in javascript is your application, because that's all you're writing. It's not a data source for anything else. If the actual data model changes, you either need to change the behavior of the app, or you can isolate the changes to the loading and saving routines. There is zero value in having an intermediate data model.

Upvotes: 1

Related Questions