简体   繁体   中英

Knockout event binding

I want to bind myFunction with change or onchange event.

This is the function which I want to bind, inside my ViewModel:

myFunction: function spinSeconds(event, ui) {
  if (ui.value >= 60) {
      $(this).spinner('value', ui.value - 60);
      $('#minutes').spinner('stepUp');
      return false;
  } else if (ui.value < 0) {
      $(this).spinner('value', ui.value + 60);
      $('#minutes').spinner('stepDown');
      return false;
  }
}

I am calling this function inside openModal() function:

function openModal() {

    //
    //some code here
    //

    $('#seconds').spinner({
        spin: spinSeconds
    });
}

I am using it as follows:

<div class="col-sm-9">
   <input id="seconds" value=10 size=2 data-bind="value: PreExecWaitMin, event: {change: myFunction}" /> minutes
</div>

And I am facing with this error:

'Uncaught ReferenceError: Unable to process binding "event: function (){return {change:myFunction} }" Message: spinSeconds is not defined'

I've searched many event binding examples but could not handle it for my issue. Thanks for any help.

The first argument to an event-bound function is $data . The second is the event. But the way to observe change events on an input is to subscribe to the bound value :

For advanced users, if you want to register your own subscriptions to be notified of changes to observables, you can call their subscribe function. For example:

 myViewModel.personName.subscribe(function(newValue) { alert("The person's new name is " + newValue); }); 

The subscribe function is how many parts of KO work internally. Most of the time you don't need to use this, because the built-in bindings and templating system take care of managing subscriptions.

More likely, the solution is to set up a computed based on the value-bound variable. The subscription is implicit.

It would be better if spinner had its own custom binding handler, though you can probably get away with this, as it seems to be just a visual effect. jQuery selectors are a significant code smell in Knockout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM