Knockout JS binding doesn't output value using simple viewmodel


Carl Weiss

I'm trying to load a simple view model that has two models: Profile (a ko.observable()) and Request (a ko.observableArray()).

When I apply the binding and then try to bind to the ether profile.field or foreach: request, I get no output, no javascript or binding errors. However, when I roll out ko.toJSON(self.profile) or ko.toJSON(self.requests), I actually get the data, it's just not bound, and I'm not sure why, what am I doing wrong.

this is my model

var Profile = function(profile) {   
    var self = this;

    self.id                  = ko.observable(profile.id);
    self.user_id             = ko.observable(profile.user_id);
    self.first_name          = ko.observable(profile.first_name);
    self.last_name           = ko.observable(profile.last_name);
    self.age                 = ko.observable(profile.age);
    self.email               = ko.observable(profile.email);
    self.area                = ko.observable(profile.area);
    self.favorite_restaurant = ko.observable(profile.favorite_restaurant);
    self.avatar              = ko.observable(profile.avatar);
    self.on_mailing_list     = ko.observable(profile.on_mailing_list);
}
var Request = function(request) {
    var self = this;

    self.id           = ko.observable(request.id);
    self.user_id      = ko.observable(request.user_id);
    self.title        = ko.observable(request.title);
    self.participants = ko.observable(request.participants);
    self.food_type    = ko.observable(request.food_type);
    self.event_date   = ko.observable(request.event_date);
    self.time_of_day  = ko.observable(request.time_of_day);
    self.area         = ko.observable(request.area);
    self.description  = ko.observable(request.description);
    self.status       = ko.observable(request.status);
}

Here is my ViewModel

var MasterViewModel = function() {
    var self = this;

    self.profile       = ko.observable();
    self.requests      = ko.observableArray();
    self.notifications = ko.observableArray();

    // load the users profile 
    $.getJSON('/profiles/load', {}, function(profile) {     
        self.profile = new Profile(ko.toJS(profile));
        console.log(ko.toJSON(self.profile));

        // load the users requests
        $.getJSON('/request/load', {}, function(requests){
            var mappedRequests = $.map(requests, function(request) {
                return new Request(request);
            });
            self.requests = mappedRequests;
            console.log(ko.toJSON(self.requests));
        });         
    });
}

Here is the simple binding I am trying to apply

<h2 data-bind="text: profile.first_name"></h2>

<ul data-bind="foreach: requests">
    <li data-bind="text: title"></li>
</ul>

Of course I would apply knockout bindings in the prepared document

  <script>
    $(document).ready(function() {
      // bind the ViewModel
      ko.applyBindings(new MasterViewModel());
    });
 </script>
Damian

You should set observables not to overwrite them with new values.

you wrote:

self.profile = new Profile(ko.toJS(profile));

You should write this:

self.profile(new Profile(ko.toJS(profile)));

Why? Because of this, ko knows that the config file has changed, so the view must be refreshed.

same question:

self.requests = mappedRequests;

should be:

self.requests(mappedRequests);

Related


Why knockout binding doesn't override ViewModel

Sudarshan I am using knockout foreach binding to bind a div. But when I click the button, no new model is created and the model keeps expanding. I want my data should be bound again and again. What am I doing wrong. Here is a demo of the problem function bindV

Why knockout binding doesn't override ViewModel

Sudarshan I am using knockout foreach binding to bind a div. But when I click the button, no new model is created and the model keeps expanding. I want my data should be bound again and again. What am I doing wrong. Here is a demo of the problem function bindV

Why knockout binding doesn't override ViewModel

Sudarshan I am using knockout foreach binding to bind a div. But when I click the button, no new model is created and the model keeps expanding. I want my data should be bound again and again. What am I doing wrong. Here is a demo of the problem function bindV

Why knockout binding doesn't override ViewModel

Sudarshan I am using knockout foreach binding to bind a div. But when I click the button, no new model is created and the model keeps expanding. I want my data should be bound again and again. What am I doing wrong. Here is a demo of the problem function bindV

CSS binding doesn't work in Knockout JS

Nehar Jain I'm new to Knockout JS and need your help with a small problem. I'm trying to conditionally bind css styles to table rows in a CSHTML page. I've added 2 lines, but using the 'visible' property only shows one for each item. Below is my cshtml code: <

If binding doesn't work in knockout.js

Deepak I'm trying to use an if statement in knockout js with data binding: For example, if if is false and the text in the div should be hidden: <!-- this is what i am trying to get working. --> <div data-bind="if: little">rank : little</div> My guess

If binding doesn't work in knockout.js

Deepak I'm trying to use an if statement in knockout js with data binding: For example, if if is false and the text in the div should be hidden: <!-- this is what i am trying to get working. --> <div data-bind="if: little">rank : little</div> My guess

Knockout.js data binding to ViewModel

Damon I'm trying to figure out KnockOut data binding and am struggling to get a simple form to bind to a ViewModel. I am using WebAPI to extract my JSON data. This is my ViewModel, when this "find" method is called, it creates a new WorkOrder object and popula

Knockout.js data binding to ViewModel

Damon I'm trying to figure out KnockOut data binding and am struggling to get a simple form to bind to a ViewModel. I am using WebAPI to extract my JSON data. This is my ViewModel, when this "find" method is called, it creates a new WorkOrder object and popula

Knockout JS calling ViewModel function in foreach binding

Luis Manez - Microsoft MVP Let's consider using a culled view model like this: var data = [{ id: 1, name: "John Doe" }, { id: 2, name: ""}, { id: 3, name: "Peter Parker"}]; var viewModel = { items: ko.observableArray(data) }; viewModel.showName = functio

Knockout.js data binding to ViewModel

Damon I'm trying to figure out KnockOut data binding and am struggling to get a simple form to bind to a ViewModel. I am using WebAPI to extract my JSON data. This is my ViewModel, when this "find" method is called, it creates a new WorkOrder object and popula

Knockout binding doesn't work

Carmel Why does knockout binding not work with the following code ko.components.register('like-widget', { template: "<input data-bind=\"value: firstName\" />" }); ko.applyBindings() $('#btnAdd').on('click', function() { var $newWidget = $('<like-widg

Knockout binding doesn't work

Carmel Why does knockout binding not work with the following code ko.components.register('like-widget', { template: "<input data-bind=\"value: firstName\" />" }); ko.applyBindings() $('#btnAdd').on('click', function() { var $newWidget = $('<like-widg

Knockout JS - visible binding with negation doesn't work

Gotham I'm trying to use visible data binding with negation, but it doesn't seem to work. I found several questions in stackoverflow that specify that NOT bindings should be used as expressions. But in my case, I'm just using the length property, so I'm not su

Typeahead.js doesn't work in Knockout 3 foreach binding

Rick I updated my web application to Bootstrap 3 and Knockout 3, so I lost the built-in typeahead in Bootstrap 2. I added typeahead.js and it works perfectly fine unless I have a typeahead in the Knockout 'foreach' binding. I've provided the code below that wo

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

Binding doesn't work with ViewModel

garden giant I want to change the fill of a rectangle based on a boolean value. I have the following class. A base class that extends INotifyPropertyChanged: public class PropertyChangedBase : INotifyPropertyChanged { public event PropertyChangedEventHandl

Binding doesn't work with ViewModel

garden giant I want to change the fill of a rectangle based on a boolean value. I have the following class. A base class that extends INotifyPropertyChanged: public class PropertyChangedBase : INotifyPropertyChanged { public event PropertyChangedEventHandl