在knockout computed observable中生成绑定的HTML

时间:2014-03-18 16:13:42

标签: knockout.js computed-observable

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

修改

所以基本上我想从计算的observable输出这个并将它绑定到计算的observable所绑定的相同viewmodel:

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

2 个答案:

答案 0 :(得分: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>

希望它能起作用:)。

Fiddle Demo

答案 1 :(得分:0)

好的,感谢@akhlesh,我找到了可能有用的东西。我遇到的唯一问题是click事件被触发了两次,但这是一个单独的问题(参见Why is this event being handled twice in knockout?)。我是这样做的:

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>