使用knockout foreach绑定绑定方法名称

时间:2014-10-14 05:36:17

标签: javascript jquery html knockout.js javascript-events

  

我正在尝试使用knockout foreach将方法名称与list元素绑定。应该在mousedown上调用方法。但是方法名称是字符串,我不知道如何使用它。   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>

4 个答案:

答案 0 :(得分:0)

您只需要在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/

只需查看我上面发送的JSFiddle链接。

答案 1 :(得分:0)

你可以像这样实现它

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

答案 2 :(得分:0)

你传递这样的方法:

<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/

答案 3 :(得分:0)

这是必需的FIDDLE

你只需要在编写函数名时删除双qquotes。

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);