jquery - MVC4 Knockout 数据绑定(bind)点击事件未触发

标签 jquery asp.net-mvc-4 knockout.js

我正在开始使用 Knockout,但遇到点击事件未触发的问题。

上面没有触发 GetWaiters 函数。不确定我做错了什么或错过了什么。

TIA

我有以下 html:

<h2>Create</h2>
<table>
    <thead>
        <tr>
            <th>WaiterId</th>
            <th>RestId</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: Waiters">
        <tr>
            <td data-bind="text: waiter_id"></td>
            <td data-bind="text: rest_id"></td>
            <td data-bind="text: name"></td>
        </tr>
    </tbody>
</table>
<br />
@Scripts.Render("~/bundles/myBundle")   
<input type="button" id="btnGetWaiters" value="Get Waiters" data-bind="click: GetWaiters" />

And following in my js file:

var WaiterViewModel = function () {
    //Make the self as 'this' reference
    var self = this;
    //Declare observable which will be bind with UI 
    self.waiter_id = ko.observable("0");
    self.rest_id = ko.observable("0");
    self.name = ko.observable("");

    //The Object which stored data entered in the observables
    var WaiterData = {
        waiter_id: self.waiter_id,
        rest_id: self.rest_id,
        name: self.name
    };

    //Declare an ObservableArray for Storing the JSON Response
    self.Waiters = ko.observableArray([]);

    GetWaiters(); //Call the Function which gets all records using ajax call

    //Function to Read All Employees
    function GetWaiters() {
        alert("fetching");
        //Ajax Call Get All Employee Records
        $.ajax({
            type: "GET",
            url: "/api/WaiterAPI",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                self.Waiters(data); //Put the response in ObservableArray
            },
            error: function (error) {
                alert(error.status + "<--and--> " + error.statusText);
            }
        });
        //Ends Here
    }
};
ko.applyBindings(new WaiterViewModel());

最佳答案

当您尝试绑定(bind)点击事件时,绑定(bind)方法应该是 View 模型的方法,但在您的实现中 GetWaiters() 被声明为私有(private)方法。像这样定义这个方法并重试:

self.GetWaiters =  function() {
    // your code
};

关于jquery - MVC4 Knockout 数据绑定(bind)点击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17963608/

相关文章:

javascript - 未捕获的语法错误 : Invalid flags supplied to RegExp constructor 'Capture'

c# - 如何通过 linq to sql 查询获取两列的记录?

Javascript 生成 HTML 代码调用 knockout

javascript - Knockout.JS : self. myObservable 不是函数,代码顺序有问题

java - 使用 jQuery-ajax 和 Servlet 的阿拉伯语数据

javascript - 如何在滚动事件上设置背景颜色不透明度的动画?

javascript - 删除后返回类?

css - 使用 Release 部署网站时样式损坏

asp.net-mvc - 在 MVC 4.0 中实现动态 Action 的路由

javascript - Knockout ObservableArray 不更新 HTML Foreach