最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing value to a function with knockout - Stack Overflow

programmeradmin1浏览0评论

I use knockout here on a very basic example where I would like to pass the value of the clicked item to the function. I tried something which doesn't work. Does someone can show me how to proceed? Maybe I'm doint the wrong way?

Thanks for your help.

<div class='liveExample'>   
    <h2 data-bind="value: 'A', click: myFunction">Aaaaa</h2>  
    <h2 data-bind="value: 'B', click: myFunction">Bbbbb</h2>
    <h2 data-bind="value: 'C', click: myFunction">Ccccc</h2>
</div>

// Here's my data model
var ViewModel = function() {

    this.myFunction = function (elm)
    {
        alert('you clicked: ' + elm);
    }
};

ko.applyBindings(new ViewModel()); // This makes Knockout get to work

jsFiddle here: /

PS: I know we can do ...click: function () { myFunction('A'); }"> but I think there is a better way.

I use knockout here on a very basic example where I would like to pass the value of the clicked item to the function. I tried something which doesn't work. Does someone can show me how to proceed? Maybe I'm doint the wrong way?

Thanks for your help.

<div class='liveExample'>   
    <h2 data-bind="value: 'A', click: myFunction">Aaaaa</h2>  
    <h2 data-bind="value: 'B', click: myFunction">Bbbbb</h2>
    <h2 data-bind="value: 'C', click: myFunction">Ccccc</h2>
</div>

// Here's my data model
var ViewModel = function() {

    this.myFunction = function (elm)
    {
        alert('you clicked: ' + elm);
    }
};

ko.applyBindings(new ViewModel()); // This makes Knockout get to work

jsFiddle here: http://jsfiddle/LkqTU/10229/

PS: I know we can do ...click: function () { myFunction('A'); }"> but I think there is a better way.

Share Improve this question edited Jul 7, 2013 at 9:45 Sergey Berezovskiy 236k43 gold badges439 silver badges466 bronze badges asked Jul 7, 2013 at 9:23 BronzatoBronzato 9,39230 gold badges125 silver badges227 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

You can get value from event target (which is h2 element):

// Here's my data model
var ViewModel = function() {

    this.myFunction = function (data, event)
    {
        debugger;
        alert('you clicked: ' + event.target.value);
    }
};

ko.applyBindings(new ViewModel());

Read more on click binding

Try:

this.myFunction = function (vm, event)
    {
        alert('you clicked: ' + event.srcElement);
    }
this.myFunction = function (val1, val2)
{
    ...;
}

and in binding you must to set:

<h2 data-bind="value: 'C', click: myFunction.bind($data, 'A', 'B')">Ccccc</h2>

This must help you. You can pass any count of values by this method.

发布评论

评论列表(0)

  1. 暂无评论