我将值作为参数传递给组件。
<badge-button params="badge: oarBadge"></badge-button>
这是包含oarBadge的viewModel:
function AppViewModel() {
var self = this;
self.oarBadge = ko.observable();
$.getJSON('/guy.json', function(data) {
var badge = new Badge('wood oar', data.badges.oar, false);
self.oarBadge(badge);
// self.oarBadge().has() returns true so the badge is being properly created with data
// returned by the ajax call
});
} // AppViewModel()
这是Badge构造函数:
function Badge(name, has, active) {
var self = this;
self.name = ko.observable(name);
self.has = ko.observable(has);
self.active = ko.observable(active);
self.disabled = ko.computed(function() {
return self.has();
});
self.toggleActive = function() {
self.active(!self.active())
};
self.toggleHas = function() {
self.has(!self.has());
};
}
这是组件的viewModel:
ko.components.register('badge-button', {
viewModel: function(params) {
var self = this;
self.badge = params.badge();
self.open = function() {
self.badge.toggleHas();
self.badge.toggleActive();
}
},
template:
'<img class="ui image" src="http://fakeimg.pl/300/" data-bind="click: open, css: { disabled: badge.disabled }" >'
});
当页面加载时,我收到错误,告诉我徽章未定义。
完整示例:https://gist.github.com/guyjacks/5a8763ff71f90e3fe8b4b153ed9a5283
答案 0 :(得分:1)
在ajax调用完成之前尝试设置一个默认对象,你也应该为observable分配observable本身,而不是这样做:
self.badge = params.badge();
你应该这样做:
self.badge = params.badge;
否则,一旦ajax请求完成,您的变量就不会更新。
以下是一个小例子:https://jsfiddle.net/b0bdru1u/1/
注意:据我所知,禁用绑定在图像中不起作用