BK52
BK52

Reputation: 934

Knockout data-bind in function

Hello I tried something but I can't do that.

HTML

<div data-bind="dxTextBox: { value:my_var }"></div>

JS

var viewModel = {
   my_var: ko.observable(''),
   StartScan:function()
    {
        mytimer = setInterval(this.DataBind, 1000);
    },
   DataBind:function()
    {
        this.my_var('hello world');
    },}return viewModel;

İf I use this

<div data-bind="dxButton: { text: 'Start', onClick: DataBind}"></div>

It is OK. This returns me "hello world"

But If I use this

<div data-bind="dxButton: { text: 'Start', onClick: StartScan}"></div>

It returns me error like this -> Error: 'Uncaught TypeError: this.my_var is not a function',

How can I solve this?

Upvotes: 1

Views: 335

Answers (1)

haim770
haim770

Reputation: 49113

When you're passing a reference to a function to be later invoked by setInterval (or setTimeout), its context would be the global scope (window in this case). Hence this.my_var would obviously return undefined.

You need to explicitly bind it to the correct context (which is the viewModel that is holding it) using .bind(this):

mytimer = setInterval(this.DataBind.bind(this), 1000);

See MDN

Upvotes: 1

Related Questions