0

我需要动态生成元素的内容。如果我只需要文本就可以了。我可以只使用计算的 observable 来构建字符串。我正在努力的部分是我还需要输出一些链接。我希望这些链接具有相同的绑定,就好像我click对锚元素进行了绑定一样。这可以在淘汰赛中做到吗?如果没有,有什么解决方案可以解决这个问题。目前我只是为 CURRENT 13 种可能性中的每一种制作一个单独的模板,但这非常难看,如果可能的话,我想避免它。

编辑

所以基本上我想从一个计算的 observable 中输出它,并将它绑定到与计算的 observable 绑定的相同的视图模型:

Some text with a <a href="javascript:void(0)" data-bind="click: ViewModelMethod">link</a>

4

2 回答 2

1

我认为您想动态生成具有点击绑定的链接。我试过这样的东西。

视图模型:-

var Vm = {
  showMsg: function () {
    alert("hello");
  },
  Link: ko.observable("")
}

Vm.GenratedLink = ko.computed(function () {
  if (this.Link() && this.Link() !== "") {
      $("#vm").append("<a id='link' href='javascript:void(0)' data-bind='click: showMsg'>" + this.Link() + "</a>");
      ko.applyBindings(Vm, $("#link")[0]);
}
}, Vm);
ko.applyBindings(Vm);

看法

 <div id="vm">Link
    <input type="text" data-bind="value: Link"/>
 </div>

希望它会工作:)

小提琴演示

于 2014-03-18T17:44:43.913 回答
0

好的,感谢@akhlesh,我发现了一些可能会起作用的东西。我唯一遇到的问题是 click 事件被触发了两次,但这是一个单独的问题(请参阅为什么在淘汰赛中此事件被处理两次?)。我是这样做的:

ko.bindingHandlers.activityContent = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
        var content = document.createElement("p");
        content.innerHTML = '<a href="javascript:void(0)" data-bind="text: user_name, click: $parent.NavigatePage.bind($data, \'profile\', user_id)"></a>';
        element.appendChild(content);
        ko.applyBindings(bindingContext, content);
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever the associated observable changes value.
        // Update the DOM element based on the supplied values here.
    }
};

var activities = ko.mapping.fromJS({Activities: [{
    "user_id": "52b5042d572b94ceadf6asdf1a2a5bc",
    "user_name": "Sean Templeton"
}, {
    "user_id": "52b5042d57asfda2b94ce61a2a5bc",
    "user_name": "Sean Templeton"
}, {
    "user_id": "52b5042d572b94ce61a2a5bc",
    "user_name": "Sean Templeton"
}, {
    "user_id": "52b5042d5asdfasdf72b94ce61a2a5bc",
    "user_name": "Sean Templeton"
}, {
    "user_id": "52basdf5042d572b94ce6asdf1a2a5bc",
    "user_name": "Sean Templeton"
}], NavigatePage: function(page, userId) { console.log(this); console.log(page); console.log(userId()); }});

ko.applyBindings(activities);

和html:

<ul data-bind="foreach: Activities">
    <li data-bind="activityContent: $data"></li>
</ul>
于 2014-03-18T19:29:43.153 回答