Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS Observable object of observables

I want to make observable object of observables. For example:

        var Project = function(id, name, custId) {
            this.id = ko.observable(id);
            this.name = ko.observable(name);
            this.custId = ko.observable(custId);
        }

        var viewModel = function() {

                    this.newUpProj = ko.observable(new Project(null,null,null));
            ...
            }

Something like this... I want newUpProject to be observable and it's properties to be observables. I also tried this.newUpProj = ko.mapping.fromJS(new Project());

Edit1: It crates the object but it's properties(id, name...) are not observables...

Edit2: Use in html:

<div class="modal-body">
                <p><input type="text" id="projNameTx" data-bind="value: newUpProj.name()" /></p><br>
                <p><select data-bind="options: customers, optionsCaption: 'Choose...', value: newUpProj.custId(), optionsText: 'name', optionsValue: 'id'" 
                    size="1"></select></p>

            </div>
            <div class="modal-footer">
                <button class="btn" data-bind="click: clearModal" aria-hidden="true">Close</button>
                <button class="btn btn-primary" data-bind="click: updateFlag() ? updateProject : addProject, enable: newUpProj.custId() && newUpProj.name()">Save</button>
            </div>

Correct values are loaded in the input and the select but the Save button never disables if the input is empty(for example), because the change don't go to the model.

like image 502
Evgeni Dimitrov Avatar asked Dec 26 '22 09:12

Evgeni Dimitrov


2 Answers

Possibly just needing to execute your newUpProj in you binding?

enable: newUpProj().custId() && newUpProj().name()

Failing that, you could try making a computed observable which is set to either true or false depending on the state of custId and name

like image 162
Thewads Avatar answered Jan 08 '23 05:01

Thewads


Managed to do it with this: http://jsfiddle.net/wF7xY/1/

var Model = function() {
    this.data = ko.observable({}); // It doesn't work
};

var Data = {
    field1: 'test1',
    field2: 'test2'
};

var model = new Model();
ko.applyBindings(model);

ko.mapping.fromJS(Data, {}, model.data);
model.data.valueHasMutated();

HTML:

<div data-bind="text: data().field1 ? data().field1() : ''"></div>

Thanks for the help.

like image 39
Evgeni Dimitrov Avatar answered Jan 08 '23 03:01

Evgeni Dimitrov