如何以编程方式将knockout js属性分配给视图模型?
我需要某种工厂结构,但我不确定最好的方法......
我正在尝试将尚不存在的属性分配给模型..
我想减少这个:
function aViewModel() {
var self = this;
self.attr1Text = ko.observable("");
self.attr1Text.focused = ko.observable(false);
self.attr2Text = ko.observable("");
self.attr2Text.focused = ko.observable(false);
self.attr3Text = ko.observable("");
self.attr3Text.focused = ko.observable(false);
self.attr4Text = ko.observable("");
self.attr4Text.focused = ko.observable(false);
self.attr5Text = ko.observable("");
self.attr5Text.focused = ko.observable(false);
}
vm = new aViewModel();
ko.applyBindings(vm);
这样的事情:
function aViewModel(attrs) {
var self = this;
for (var attr of attrs){
self[attr+"Text"] = ko.observable("");
self[attr+"Text"]["focused"] = ko.observable(false);
}
}
attr_list = ["attr1", "attr2", ..., "attrN"]
vm = new aViewModel(attr_list);
ko.applyBindings(vm);
让它真正起作用。
这有效:
function aViewModel() {
var self = this;
}
vm = new aViewModel();
attr_list = ["attr1", "attr2", ..., "attrN"]
for (var attr of attr_list){
self[attr+"Text"] = ko.observable("");
self[attr+"Text"]["focused"] = ko.observable(false);
}
ko.applyBindings(vm);
但是更多的封装会很好,所以我只创建了一个包装函数,
function createGrid(things, data){
vm = new gridViewModel(things);
for (var thing of things){
vm[thing+"Text"] = ko.observable("");
vm[thing+"Text"]["focused"] = ko.observable(false);
}
\\ other stuff with data
return vm;
}
然后使用
vm = createGrid(things, data)
ko.applyBindings(vm);
我觉得我在回答自己的问题。但是有更好的方法吗?
答案 0 :(得分:0)
使用knockout mapping插件
var modelClass = function(data){
ko.mapping.fromJS(data,this);
//additional values or computed
this.full_name = ko.computed(function(){
return ko.unwrap(this.first_name) + ' ' + ko.unwrap(this.last_name);
}
}
var mapping = {
create : function(options){
return new modelClass(options.data);
}
}
var viewModel = function(){
this.myModel = ko.mapping.fromJS(data,mapping);
}