javascript Knockout JS 在加载时调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10332723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:30:30  来源:igfitidea点击:

Knockout JS calling functions on load

javascriptfunctionviewmodelknockout.js

提问by Aidos

I am using Knockout.js to build a client-side view model. In my view model I would like to expose some functions that can be bound to elements in the page (typical MVVM model). I only want these functions to be called in response to a click event from a button, however they are been called when the view model is been constructed...

我正在使用 Knockout.js 来构建客户端视图模型。在我的视图模型中,我想公开一些可以绑定到页面元素的函数(典型的 MVVM 模型)。我只希望在响应来自按钮的单击事件时调用这些函数,但是在构建视图模型时会调用它们...

I have defined my model like this:

我已经这样定义了我的模型:

<script type="text/javascript">
var ViewModel = function(initialData) {
    var self = this;

    self.id = initialData;
    self.isSubscribed = ko.observable(false);
    self.name = ko.observable();

    self.SubscribeToCategory = function () {
        $.ajax({
            url: '@Url.Action("Subscribe", "Category")',
            type: 'POST',
            data: {
                categoryId: self.id
            },
            success: function () {
                self.isSubscribed(true);
            },
            failure: function () {
                self.isSubscribed(false);
            }
        });

        alert('Subscribing...');
    };

    self.UnsubscribeFromCategory = function () {
        $.ajax({
            url: '@Url.Action("Unsubscribe", "Category")',
            type: 'POST',
            data: {
                categoryId: self.id
            },
            success: function () {
                self.isSubscribed(false);
            },
            failure: function () {
                self.isSubscribed(true);
            }

        }); 

        alert('Unsubscribing...');
    };

    self.LoadCategory = function () {
        $.ajax({
            url: '@Url.Action("GetCategory", "Category")',
            type: 'POST',
            async: true,
            data: {
                categoryId: self.id
            },
            dataType: 'json',
            success: function (data) {
                self.isSubscribed(data.IsSubscribed);
                self.name(data.Name);
            }
        });
    };

    self.LoadCategory();
};


$(document).ready(function () {
    var data = '@Model';
    var viewModel = new ViewModel(data);
    ko.applyBindings(viewModel);
});

When I execute the code however, the two alerts fire automatically, but I am not expecting them to. I am using ASP MVC4, and the HTML that is using the view model is below:

然而,当我执行代码时,两个警报会自动触发,但我并不期望它们会触发。我正在使用 ASP MVC4,使用视图模型的 HTML 如下:

<p>
    ID: <span data-bind="text: id"></span>
</p>
<div id="subscribe" data-bind="visible: isSubscribed == false">
    <button data-bind="click: SubscribeToCategory()">Subscribe</button>
</div>
<div id="unsubscribe" data-bind="visible: isSubscribed == true">
    <button data-bind="click: UnsubscribeFromCategory()">Unsubscribe</button>
</div>
<div>
    Category Name: <span data-bind="text: name"></span>
    Is Subscribed: <span data-bind="text: isSubscribed"></span>
</div>

I've looked through the tutorials online and some other knockout samples, as well as other places in my code where I have used knockout, but I cannot see why the two functions (SubscribeToCategory and UnsubscribeFromCategory) are firing on document load.

我已经浏览了在线教程和其他一些淘汰赛示例,以及我使用过淘汰赛的代码中的其他地方,但我不明白为什么这两个函数(SubscribeToCategory 和 UnsubscribeFromCategory)在文档加载时触发。

回答by Ryan Fiorini

jsfiddle

提琴手

It took me a second, but ended up being a simple fix. remove the () from your data-bind="click: SubscribeToCategory()" and make both you click handlers this data-bind="click: SubscribeToCategory" and data-bind="click: UnsubscribeFromCategory"

我花了一秒钟,但最终是一个简单的修复。从您的 data-bind="click: SubscribeToCategory()" 中删除 () 并使您点击处理程序成为 data-bind="click: SubscribeToCategory" 和 data-bind="click: UnsubscribeFromCategory"

回答by Aidos

It appears that the brackets in the function name in the binding <button data-bind="click: SubscribeToCategory()">Subscribe</button>is the problem.

绑定中函数名中的括号似乎<button data-bind="click: SubscribeToCategory()">Subscribe</button>是问题所在。

The ()'s shouldn't be there. So it should look like:

() 不应该在那里。所以它应该看起来像:

<button data-bind="click: SubscribeToCategory">Subscribe</button>