2

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.net/RcxVj/

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

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

2 Answers 2

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.

1
  • This is what was causing my script to fail. I was trying in jsfiddle rather than creating an actual file. As @bluetoft mentioned, knockout has to be loaded within the body to work in jsfiddle. Thanks for all the help.
    – shriek
    Commented Sep 28, 2013 at 23:17
2

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.com/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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.