Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call function outside viewmodel on knockout?

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.

like image 282
shriek Avatar asked May 04 '26 02:05

shriek


2 Answers

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.

like image 63
Chirag Arvadia Avatar answered May 05 '26 17:05

Chirag Arvadia


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);
like image 42
mg1075 Avatar answered May 05 '26 16:05

mg1075



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!