Knockout firing click binding on applyBindings

后端 未结 2 1078
长情又很酷
长情又很酷 2020-12-23 16:11

Recently I\'ve separated out ViewModel to a separate JavaScript file.

var Report = (function($) {
    var initialData = [];
    var viewModel = {
        rep         


        
相关标签:
2条回答
  • 2020-12-23 16:46

    The reason is, that you're indeed invoking the preview function (because writing functionName means referring to the function, writing functionName() means calling it).

    So data-bind="click: Report.preview" would be working as expected, but without handing over the parameter.

    As the manual states (on a different topic, but this still applies):

    If you need to pass more parameters, one way to do it is by wrapping your handler in a function literal that takes in a parameter, as in this example:

    <button data-bind="click: function(data, event) { myFunction(data, event, 'param1', 'param2') }">
        Click me
    </button>
    

    or in your case:

    data-bind="click: function() { Report.preview('url/to/report') }"
    

    Another solution would be to make preview() return a function (pretty much the same thing actually):

    preview: function(path) {
        return function() {
            // ...
        }
    }
    
    0 讨论(0)
  • 2020-12-23 16:46

    Another solution is to use 'bind' construct:

    data-bind="click: Report.preview.bind($data, 'url/to/report')" 
    

    where the first parameter to bind() will become the 'this' in the called function.

    0 讨论(0)
提交回复
热议问题