无法处理绑定,Knockout和foreach问题

时间:2014-10-04 13:41:48

标签: javascript jquery knockout.js

我有一个ViewModel,可以处理评论字段的一些函数。我有一个编辑功能的问题,该功能应该切换为真/假,以便在html中的foreach字段中查看几个标签。在控制台日志中,我收到此错误:

未捕获的ReferenceError:无法处理绑定“visible:function(){return!editable()}” 消息:未定义可编辑

这是我的代码:

      function Comment() {
    var self = this;

    self.nickname = ko.observable();
    self.newMsg = ko.observable();
    self.editable = ko.observable(false);

    self.sendEntry = function () {
     vm.selectedComment(new Comment());

        if (self.newMsg() !== "" && self.nickname() !== "") {

            $.post(writeUrl, "entry=" + ko.toJSON(self));
            self.newMsg("");
        }
        vm.cSection().getNewEntries();
    };
    self.deleteComment = function () {
        vm.comments.remove(self);
    };

     self.editComment = function () {
        self.editable(!self.editable());
    };
}
function commentSection() {
    var self = this;
    self.timestamp = 0;

    self.getNewEntries = function () {

        $.getJSON(readUrl, "timestamp=" + self.timestamp, function (comments) {
            for (var i = 0; i < comments.length; i++) {
                var entry = comments[i];
                if (entry.timestamp > self.timestamp) {
                    self.timestamp = entry.timestamp;
                }
                vm.comments.unshift(entry);
            }
             self.getNewEntries();
        });
    };

}

function ViewModel(){
    var self = this;

    self.cSection=ko.observable(new commentSection());
    self.comments = ko.observableArray();
    self.selectedComment = ko.observable(new Comment());

    //self.cSection().getNewEntries();
}
var vm=new ViewModel();
ko.applyBindings(vm);
vm.cSection().getNewEntries();

});

HTML部分:

<div>
<ul data-bind="foreach: comments">
                        <li class="ul3">
                            <span class="author" data-bind="text: nickname, visible: !editable(), click: editComment"></span>
                            <input type="text" data-bind="value: nickname, visible: editable()"/>:
                            <div>  

                                <span class="comment" data-bind="text: newMsg, visible: !editable(), click: editComment"></span>
                                <textarea class="myComment" type="text" data-bind="value: newMsg, visible: editable()"></textarea>

                                </div>
                            <button data-bind="click: editComment, text: editable() ? 'Save' : 'Edit comment'"></button> 
                                <button data-bind="click: deleteComment">Delete</button>
                        </li>
                    </ul>
                </div>

如果我的问题不清楚,请告诉我。提前谢谢!

0 个答案:

没有答案