javascript KnockoutJS Observable 的 Observable 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14815047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
KnockoutJS Observable object of observables
提问by Evgeni Dimitrov
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());
像这样的东西......我想newUpProject
成为可观察的,它的属性是可观察的。我也试过this.newUpProj = ko.mapping.fromJS(new Project());
Edit1: It crates the object but it's properties(id, name...) are not observables...
Edit1:它包装对象,但它的属性(id,名称...)不是可观察的...
Edit2: Use in html:
Edit2:在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.
在输入和选择中加载正确的值,但如果输入为空(例如),则保存按钮永远不会禁用,因为更改不会进入模型。
回答by Thewads
Possibly just needing to execute your newUpProj in you binding?
可能只需要在绑定中执行 newUpProj 吗?
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
如果失败,您可以尝试根据 custId 和 name 的状态将计算的 observable 设置为 true 或 false
回答by Evgeni Dimitrov
Managed to do it with this: http://jsfiddle.net/wF7xY/1/
设法做到这一点: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:
HTML:
<div data-bind="text: data().field1 ? data().field1() : ''"></div>
Thanks for the help.
谢谢您的帮助。