简体   繁体   中英

Knockout JS how to bind observable of object html bind

I need to bind to cshtml view a ko.observable which holds an object defined by me. To clarify let's go with a small piece of code:

ViewModel:

define('vm.test',
['ko', 'model'],
function(ko, model) {

    var
        myObject = ko.observable(new model.MyModel()),

        someFunction = function() {
            // Here goes some code which obtains object data
            myObject.property1 = data.test;
            myObject.property2 = data.test2;
            myObject.property3 = data.test3;
        };


    return {
        myObject: myObject,
        someFunction: someFunction 
    };
});

Model:

define('model.myModel',
['ko'],
function (ko) {

    var
        MyModel= function () {
            var self = this;
            self.property1= ko.observable();
            self.property2= ko.observable();
            self.property3= ko.observable();
            self.isNullo = false;
            return self;
        };

    MyModel.Nullo = new MyModel()
        .property1('')
        .property2('')
        .property3('');
    MyModel.Nullo.isNullo = true;

    return MyModel;
});

And what I want to achieve is to bind each property of myObject to separate, let's say, in HTML. I have tried to do this in several ways, but unfortunately without any success. Does anyone have an idea how to bind such an object to separate spans?

What I have already tried and did not work for me:

Approach 1:

    <div data-bind="with: myObject">
        <span data-bind="text: $data.property1"></span>
        <span data-bind="text: $data.property2"></span>
        <span data-bind="text: $data.property3"></span>
    </div>

Approach 2:

    <span data-bind="text: myObject.property1"></span>

Approach 3:

    <span data-bind="text: myObject().property1"></span>

And none of those works. The binding with the view model works, as well as the whole structure, since other properties (simple observables or observableArrays) I use in the vm are binded without any problems to the view. What is more, if I write to console the content of myObject from within the view model, it is filled with the values I wanted. However, the values are not assigned to the view.

Perhaps changing this:

myObject = ko.observable(new model.MyModel()),

to this:

myObject = new model.MyModel(),

EDIT:

Demo here .

EDIT 2:

Please note that you cannot update your observables like this:

myObject.property1 = data.test;

but instead, you need to make a function call:

myObject.property1(data.test);

您可以在父HTML DOM中使用data-bind =“ with:Modelobject”,这将使每个对象属性都可观察到

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