knockout.js 使用敲除foreach绑定绑定方法名称

y1aodyip  于 2022-11-10  发布在  其他
关注(0)|答案(4)|浏览(132)

我尝试使用knockout foreach将方法名称与列表元素绑定。方法应该在mousedown上调用,但是方法名称是字符串,我没有; I don’我不知道怎么用。
JsFiddle Link
Javascript语言

var model = {};
        var data1 = [{ Name: "hi", Method: "a" }, { Name: "hello", Method: "b" }, { Name: "bye", Method: "c" }];

        model.data = ko.observableArray(data1);

        function a() {
            alert('i am a');
        }

        function b() {
            alert('i am b');
        }

        function c() {
            alert('i am c');
        }

        ko.applyBindings(model);

HTML格式

<ul data-bind="foreach: data">
    <li>
        <label data-bind="text: Name, event: { mousedown: Method }"></label>
    </li>
</ul>
mzaanser

mzaanser1#

您只需要在Viewmodel定义中定义函数,如Here所示
例如,您需要将其用作::

var model = {};
            var data1 = [{ Name: "hi", Method: 
            function a() {
                alert('i am a');
            } }];

            model.data = ko.observableArray(data1);

            ko.applyBindings(model);

http://jsfiddle.net/egbh0x3z/2/
只是 checkout JSFiddle链接,我发送以上。

bmvo0sr5

bmvo0sr52#

你可以这样做

var model = {};
var data1 = [
        { Name: "hi", Method: "a" }, 
        { Name: "hello", Method: "b" }, 
        { Name: "bye", Method: "c" }
];

model.data = ko.observableArray(data1);
model.Method = function(str){
    if(str == 'a'){
        a()
    }else if(str == 'b'){
        b()
    }else{
        c()
    }
}
ko.applyBindings(model);

function a() {
    alert('i am a');
}

function b() {
    alert('i am b');
}

function c() {
    alert('i am c');
}

并查看

<ul data-bind="foreach: data">
    <li>
        <label data-bind="text: Name, event: { mousedown: $root.Method.bind($data,Method) }"></label>
    </li>
</ul>

Demo(第一个字母)

blmhpbnm

blmhpbnm3#

您可以像这样传递方法:

<label data-bind="text: Name, event: { mousedown: Method }"></label>

你的模型应该是这样的:

var data1 = [{ Name: "hi", Method: a }, { Name: "hello", Method: b }, { Name: "bye", Method: c }];

http://jsfiddle.net/egbh0x3z/4/

83qze16e

83qze16e4#

这里是必需的FIDDLE
您只需要在编写函数名时删除双引号。

var model = {};
        var data1 = [{ Name: "hi", Method: a }, { Name: "hello", Method: b }, { Name: "bye", Method: c }];

        model.data = ko.observableArray(data1);

        function a() {
            alert('i am a');
        }

        function b() {
            alert('i am b');
        }

        function c() {
            alert('i am c');
        }

        ko.applyBindings(model);

相关问题