0

please go through the link: http://jsfiddle.net/nn0mfe48/1/

Here i am able to use knockout WITH binding when i use object literal, but when i change it to function same code doesn't work.

Works:

var profileModel =  {
    first: ko.observable("Bob"),
    last: ko.observable("Smith"),
};

Doesn't work:

var  profileModel = function() {
    this.firstname= ko.observable("Bob");
    last: ko.observable("Smith");
};

what do i need to change in code to make it work. My need of hour is to pass knockout viewmodel object to viewmodel and bind the value dynamically instead of hard coding the values.

i had gone through the link : Difference between knockout View Models declared as object literals vs functions

but couldn't understand how can make use in my case. hope i explained clearly and understandable. any help in this regard is appreciated.thanks in advance.

Community
  • 1
  • 1
ravibhat
  • 811
  • 1
  • 7
  • 19

2 Answers2

2

The code in your question you are mixing object literal syntax w/ variable assignment syntax. Also, in the function you should be assigning this to a self/that variable to alleviate scope issues. It also makes using ko.computed() a lot nicer.

var profileMod = function() { 
     var self = this;
    self.first = ko.observable("Bob");
    self.last = ko.observable("Smith");
    }

I've updated your fiddle http://jsfiddle.net/nn0mfe48/3/

Stephen Gilboy
  • 5,572
  • 2
  • 30
  • 36
  • Thanks Stephen, it worked. :), but getting error in console like : referenceError: Unable to process binding "with: function (){return shell }" Message: Unable to process binding "with: function (){return $root.profile }" . Even after this error it binds the data. – ravibhat Oct 03 '14 at 19:58
  • It's because I left off the selectedchoice in my definition. http://jsfiddle.net/nn0mfe48/4/ – Stephen Gilboy Oct 03 '14 at 20:04
  • Ya, got it after replying to post. thanks mate, appreciate your immediate response. – ravibhat Oct 03 '14 at 20:08
1

Once you've created your view model correctly:

var profileModel = function() {
    this.firstname = ko.observable("Bob");
    this.lastname = ko.observable("Smith");
};

Make sure you create a new instance of it before binding:

var vm = new profileModel();

And bind that:

ko.applyBindings(vm);

Also, be careful with your use of the with binding. You've created a context around your shell model which forces you to use $root to access your profile view model.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • You're welcome. Arguably though, *all* of your models should be built this way and not as object literals. You can compose or aggregate all the models you want, but they should be defined consistently. And if you want events to bubble, you can wrap instances of other models in `ko.observable` too (e.g. `this.profile = ko.observable(new profileModel());`). – Cᴏʀʏ Oct 03 '14 at 20:09