2016-03-10 109 views
0

我想綁定myFunction與更改或onchange事件。敲除事件綁定

這就是我想結合,我的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; 
    } 
} 

我打電話裏面openModal此功能()函數:

function openModal() { 

    // 
    //some code here 
    // 

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

我如下使用它:

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

而且我現在面臨這個錯誤:

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

我搜索了很多事件綁定的例子,但無法處理我的問題。謝謝你的幫助。

+0

我正在使用這些spinners:http://jsfiddle.net/xHzMw/228/我認爲使用change事件進行綁定是正確的。 – ismailcem

回答

1

The first argument to an event-bound function$data。第二個是事件。但是,觀察的輸入變化事件的方式是subscribe到綁定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.

更可能的是,該解決方案是一種基於價值綁定變量建立computed。訂閱是隱含的。

如果spinner擁有自己的自定義綁定處理程序,雖然您可能會擺脫這種情況,但它似乎只是一種視覺效果,會更好。 jQuery選擇器是Knockout中的重要代碼味道。

+0

爲了保持完整性,請包含訂閱示例。 – Michael

+1

@Michael查看擴展的答案 –