vendredi 1 avril 2016

KnockoutJS : separate model from modelview

I have a model being used by multiple view models, and i need some other javascript components to update the model, observed by my vm's. I have no idea how to do this since in the tutorial, they "mix" the model in the viewmodel.

Here is my code :

var ConversationModel = {
    conversations: ko.observableArray(),
    open: function(userId){
        for(var i = 0; i < this.conversations.length; i++){
            if(this.conversations[i].userId == userId){
                return;
            }
        }

        var self = this;
        var obj = ko.observable({
            userId: userId
        });

        self.conversations.push(obj);

        UserManager.getUserData(userId, function(user){
            $.getJSON(Routes.messenger.getConversation, "receiver=" + userId, function(data){
                obj.receiver = user;
                obj.data = data;
            });
        });
    }
};

function ConversationDialogViewModel(){
var self = this;

this.conversations = ko.computed(function(){
    return ConversationModel.conversations;
});

console.log(this.conversations());

this.conversations.subscribe(function(context){
    console.log(context);
});

}




Aucun commentaire:

Enregistrer un commentaire