0

I am working on an application which has DurandalJS 2.0.1. I have written a viewmodel, basically I want to implement a master viewmodel that has multiple viewmodels (e.g. account viewmodel has register and login sub viewmodels)

define(['knockout'],function (ko) {

    var register = function(){
        var self = this;
        self.Welcome = "Register";
        self.Username = ko.observable();
        self.Password = ko.observable();

    }
    var login= function(){
        var self = this;
        self.Welcome = "Login";
        self.Username = ko.observable();
        self.Password = ko.observable();
    }   
    var account = {
        testVariable : "Hello Cruel World!",
        register : register,
        login : login
    };

    return account;

});

View is :

<h2 data-bind="text: testVariable"></h2>
<h2 data-bind = "text: register().Welcome"></h2>
<h2 data-bind = "text: login().Welcome"></h2>

testVariable is being displayed correctly but I can't make register().Welcome, login().Welcome or tried register.Welcome or login.Welcome working.

Any idea how can I get it working?

Rahul Patil
  • 5,656
  • 6
  • 37
  • 65
  • 1
    You've written the `login` and `register` methods as constructors, so you need to do `new login()` and `new register()`. I'd suggest doing that immediately, when creating the `account` viewmodel, instead of doing it in the bindings (which would likely give you other problems in the length). – Robert Westerlund May 22 '14 at 12:31
  • Thanks mate, I've managed to find an answer for my own question with little different approach but it works :-) I will post it here itself.. – Rahul Patil May 23 '14 at 05:29

1 Answers1

0

Here's how you can tackle such situations... @robert.westerlund is right, if that is function then you've to create new object of each function before proceeding..

define(['plugins/http', 'durandal/app', 'jquery', 'knockout'], function (http, app, $, ko) {



    var loginVM = {
        Welcome : "Hello Login",
        Username : ko.observable(),
        Password : ko.observable(),
        rememberMe : ko.observable(false),

        Login : function (obj, event) {
              //Do the login stuff
        }
    };

    var registerVM = {
        Welcome : "Hello Register",
        Username : ko.observable(),
        Password : ko.observable(),
        ConfirmPassword : ko.observable(),

        Register : function (obj, event) {
              //Do the register stuff
        }
};

    return {
        login : loginVM,
        register: registerVM
    };


});

VIEW

<div data-bind="with:login">
     <h2 data-bind = "text: Welcome"></h2>
</div>
<div data-bind="with:register">
     <h2 data-bind = "text: Welcome"></h2>
</div>

Instead of writing functions, I wrote object literals. That worked pretty well :-)

Rahul Patil
  • 5,656
  • 6
  • 37
  • 65