【发布时间】:2013-04-20 11:30:00
【问题描述】:
我的任务是为链接动态形成“href”,每次更改附加的可观察对象时。这是一个示例的链接: JS Fiddle example link
在实现这一点时我遇到了两个问题:
-
当我尝试传递一些字符串 + 计算的 observable 时,我得到了计算 函数列表,而不是它的值。
<a data-bind="attr: {href : '#someHash/' + getHref(10)}">Link</a>链接如下:
http://fiddle.jshell.net/3DAfQ/1/show/#someHash/function h(){if(0<arguments.length)return"function"===typeof v?v.apply(d,arguments):j(Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.")),this;n||g();b.r.Wa(h);return l}我觉得这甚至不太合适。
-
其次,当我尝试更改可观察的、计算的依赖时,链接不会改变。
<a href="#" data-bind="click: changeStoreHref(20)">change Link</a> self.changeStoreHref = function(num) { self.storeHref(num); };
这是 HTML 代码:
<a data-bind="attr: {href : '#someHash/' + getHref(10)}">Link</a>
<a href="#" data-bind="click: changeStoreHref(20)">change Link</a>
还有knockoutjs:
function viewModel()
{
var self = this;
self.storeHref = ko.observable('ten');
self.getHref = function(id)
{
return ko.computed({
read: function()
{
self.storeHref(id);
return self.storeHref();
}
});
};
self.changeStoreHref = function(num)
{
self.storeHref(num);
};
}
ko.applyBindings(new viewModel());
我提醒您,您可以通过以下链接查看此示例:JS Fiddle example link 谢谢。
【问题讨论】:
标签: knockout.js computed-observable