【问题标题】:Knockout unable to parse binding internal method淘汰赛无法解析绑定内部方法
【发布时间】:2013-03-01 19:18:25
【问题描述】:

我可能遗漏了一些非常简单的东西,但谁能指出我在这里做错了什么?

非常感谢。

<div data-bind="foreach: agencies">
    <div data-bind="text:name"></div>
    <div data-bind="text:email"></div>
    <button data-bind="click: removeAgency">remove</button>
</div>

<script type="text/javascript">

    var agency = [{
        name : ko.observable('a'),
        email : ko.observable('b')
    }, {
        name: ko.observable('c'),
        email: ko.observable('d')
    }];

    var vm = {
        agencies: ko.observableArray(agency),
        removeAgency: function(agency) {
            this.agencies.remove(agency);
        }
    };

    ko.applyBindings(vm);
</script>

这是我得到的错误:未捕获的错误:无法解析绑定。 消息:ReferenceError:removeAgency 未定义; 绑定值:点击:removeAgency

【问题讨论】:

    标签: javascript knockout.js knockout-2.0


    【解决方案1】:

    您正在绑定到该 html 中的代理,但您的方法在您的视图模型上。尝试类似:

    <button data-bind="click: $parent.removeAgency">remove</button>
    

    您可能需要重新调整您的虚拟机以使范围正确:

    var ViewModel = function(){
        var self = this;
        self.agencies = ko.observableArray(agency),
        self.removeAgency = function(agency) {
            self.agencies.remove(agency);
        }
    };
    
    var vm = new ViewModel();
    

    我不得不承认,有时我仍然对范围感到困惑,但请尝试一下,看看会发生什么。

    【讨论】:

    • 不是那样的,但这正是你所需要的:)
    • 感谢@Paul 的快速回复。现在它说:无法调用未定义的方法“删除”
    【解决方案2】:

    工作示例:

    http://jsfiddle.net/marko4286/7RDc3/2034/
    

    阅读文档http://knockoutjs.com/documentation/foreach-binding.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-03
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 2016-01-22
      • 2015-03-23
      相关资源
      最近更新 更多