admin管理员组

文章数量:1288087

Let's say I want to call my plain javascript function on one of my data-binding. Is it possible to do so? I have tried:-

<span data-bind = "click : outsideFn() ">hi</span>

<span data-bind=" click : function() { outsideFn() } ">hi</span?

Obviously, my attempt was unsuccessful.

/

Edit:- Adding jsfiddle on the tag as this seems to be an issue with jsfiddle.

Let's say I want to call my plain javascript function on one of my data-binding. Is it possible to do so? I have tried:-

<span data-bind = "click : outsideFn() ">hi</span>

<span data-bind=" click : function() { outsideFn() } ">hi</span?

Obviously, my attempt was unsuccessful.

http://jsfiddle/RcxVj/

Edit:- Adding jsfiddle on the tag as this seems to be an issue with jsfiddle.

Share Improve this question edited Sep 28, 2013 at 23:18 shriek asked Sep 28, 2013 at 2:39 shriekshriek 5,8438 gold badges52 silver badges83 bronze badges 2
  • 1 Have you tried this outside of jsfiddle? I tweaked it a bit and got it to work. It looks like there are just script loading issues.jsfiddle – bluetoft Commented Sep 28, 2013 at 3:47
  • I did only try in jsfiddle and you're right it does actually work. Placing my javascript code at the end of the body element and loading the knockout library on the head did the trick. Thank you. – shriek Commented Sep 28, 2013 at 6:49
Add a ment  | 

2 Answers 2

Reset to default 9

Yes it is possible to call plain javascript function in data-binding. Try it in your project, it's working. There may be some problem in the jsfiddle script.

Yes, you can. Please note the official Knockout documentation for the click binding:

You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject.someFunction.


Working example:

https://jsbin./ciwofayegi/1/edit?html,css,js,output

HTML

<span data-bind="text: txt, click: outsideFn"></span>

Javascript

var outsideFn = function () {
    alert("outside function"); 
};

var vm = {
    "txt": ko.observable("some text")
};

ko.applyBindings(vm);

本文标签: javascriptCan I call function outside viewmodel on knockoutStack Overflow