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

查看:258
本文介绍了Knockout在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')" />

问题当以下行在$中执行时调用预览方法(文档).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() {
        // ...
    }
}

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

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