简体   繁体   中英

Knockout: how can I pass a model to a javascript object literal?

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.

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM