简体   繁体   English

在敲除绑定中传递未知函数(foreach)-有可能吗?

[英]Passing an unknown function in a knockout binding (foreach) - is it possible?

For a simple example, lets say this is my repeater: 举一个简单的例子,可以说这是我的中继器:

<ul data-bind="foreach: items">
    <li data-bind="text: property1, attr: { onclick: some_unknown_function }"></li>
</ul>

I want whoever is using this code to be able to pass in a function of their choosing, NOT in the model itself that will run onclick - is that possible? 我希望任何使用此代码的人都可以传递他们选择的功能,而不是传递给将运行onclick的模型本身-可能吗? Would there be a way to assign it to the model and set it as the click binding? 是否可以将其分配给模型并将其设置为单击绑定? I can't seem to figure this out... 我似乎无法弄清楚...

Figured out a pretty easy way, sometimes I forget how literal JS is... 想出了一种非常简单的方法,有时我忘记了文字JS是多么的...

Changed my repeater to this: 将我的中继器更改为:

<ul data-bind="foreach: items">
    <li data-bind="text: property1, click: myClick }"></li>
</ul>

And my model to this: 我的模型是这样的:

function Item(options) {
    var self = this;
    options = options || {};

    self.property1 = ko.observable(options.property1 || '');
    self.onclick = options.onclick || null;

    self.myClick = function () {
        if (self.onclick != null) {
            self.onclick()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM