击倒在 applyBindings 上触发点击绑定 [英] Knockout firing click binding on applyBindings

查看:19
本文介绍了击倒在 applyBindings 上触发点击绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我将 ViewModel 分离到一个单独的 JavaScript 文件中.

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

var Report = (function($) {
    var initialData = [];
    var viewModel = {
        reports: ko.observableArray(initialData),
        preview: function(path) {
            // preview report
        },
        otherFunctions: function() {}
    };
    return viewModel;
})(jQuery);​

这里是 HTML 和 Knockout 相关代码

Here is the HTML and Knockout related code

<script type="text/javascript" src="path/to/report/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        ko.applyBindings(Report, document.body);
    });
</script>

HTML 用户界面有一个按钮,点击该按钮是数据绑定到视图模型中的预览功能

HTML user interface has a button on which click is data bind to preview function in the view model

<input type="button" name="Preview" id="Preview" class="btnPreview" 
    data-bind="click: Report.preview('url/to/report')" />

问题 在 $(document).ready() 函数中执行以下行时调用预览方法

Problem preview method is called when the following line execute in $(document).ready() function

ko.applyBindings(Report, document.body); 

也就是说,没有用户点击预览按钮预览功能被触发.这种行为的原因是什么?当我在 HTML 页面本身中查看模型 JavaScript 时,整个工作正常.

That is without user clicking on the Preview button preview function is fired. What could be the reason for this behavior? The whole stuff was working fine when I'd view model JavaScript in the HTML page itself.

推荐答案

原因是,你确实在调用预览函数(因为写functionName意味着引用函数,写functionName() 表示调用它).

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

所以 data-bind="click: Report.preview" 会按预期工作,但不会传递参数.

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>

或者你的情况:

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

另一种解决方案是使 preview() 返回一个函数(实际上几乎相同):

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

preview: function(path) {
    return function() {
        // ...
    }
}

这篇关于击倒在 applyBindings 上触发点击绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆