【问题标题】:Knockout viewmodel function not accessible淘汰视图模型功能无法访问
【发布时间】:2013-08-02 23:31:25
【问题描述】:

现在正在运行。以下是此代码的修改版本。 var data = $.getJSON("URL", null, function (result) {

                        var notes = function () {
                            self = this;
                            self.notes = ko.observableArray(result);
                            self.deleteNote = function (note) {
                                $.ajax({
                                    url: "URL" + this.ID,
                                    dataType: "json",
                                    type: "GET",
                                    success: function (d) {
                                        self.notes.remove(note);
                                    }
                                });
                            };

                            self.addNote = function () {
                                var note = $("#txtNote").val();
                                $.ajax({
                                    url: "URL",
                                    type: "POST",
                                    data: { 'note': note },
                                    datatype: "json",
                                    success: function (data) {
                                        self.notes.push({ Description: note, ID: data.ResponseData.id, CreateDate: data.ResponseData.createDate });
                                    }
                                });
                            }


                        }
                        ko.applyBindings(new notes());
                    });

谢谢, JSHunjan

【问题讨论】:

  • 这个问题现在已经修复,我已经相应地修改了我的问题。
  • 我不确定如何将此问题标记为已修复。请关闭此问题。

标签: knockout.js


【解决方案1】:

这行可能是问题

viewModel.notes.remove(this);

this指向当前函数,所以remove函数不知道要删除什么。

如果您使用click 绑定,我假设您这样做,实际注释将传递给函数,这应该是您的解决方案(未经测试)。我添加了note 变量

   removePerson: function (note) {
        $.ajax({
            url: "URL",
            type: "POST",
            success: function () {
                viewModel.notes.remove(note);
            }
        })
    }

在此处阅读文档:http://knockoutjs.com/documentation/click-binding.html

【讨论】:

  • 感谢您的快速回复。我试过这个但没有运气。这是我在 Firefox 中收到的错误。错误:无法解析绑定。消息:ReferenceError:removePerson 未定义;绑定值:点击:removePerson
  • @JSHunjan 您可能在foreach: notes 绑定体内的元素中使用它。当前上下文将是 notes 元素,而不是您的整个模型。试试click: $parent.removePerson。另外,如果你必须写像$('#txtNote').val() 这样的东西,那么使用 Knockout 有什么意义呢?只需使用value 绑定即可。
  • 是的,您必须使用$parent.removePerson$data.removePerson。不只是删除人
猜你喜欢
  • 2012-01-18
  • 2015-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多