Knockout JS Binding Null Binding

时间:2014-02-10 18:06:43

标签: javascript knockout.js

这是fiddle

我有这个HTML:

<div class="margin:0px; padding:0px; outline:0; border:0;" data-bind="with: notesViewModel">
        <table class="table table-striped table-hover" data-bind="with: notes">
            <thead><tr><th>Date Logged</th><th>Content</th><th>Logged By</th><th></th></tr>
            </thead>
            <tbody data-bind="foreach: allNotes">
                <tr>
                    <td data-bind="text: date"></td>
                    <td data-bind="text: compressedContent"></td>
                    <td data-bind="text: logged"></td>
                    <td><img src="/images/detail.png" data-bind="click: $root.goToNote.bind($data, $index())" width="20" alt="Details"/></td>
                </tr>
            </tbody>
        </table>

        <div class="noteView" data-bind="with: chosenNote">
            <div class="info">
                <p><label>Date:</label><span data-bind="text: date"></span></p>
                <p><label>Logged:</label><span data-bind="text: logged"></span></p>
            </div>
            <p class="message" data-bind="html: content"></p>
            <button class="btn btn-default" data-bind="click: $root.toNotes">Back to Notes</button>
        </div>

        <div class="editor-label" style="margin-top:10px">
            Notes
        </div>
        <div class="editor-field">
            <textarea id="contact_note" rows="5" class="form-control" data-bind="value: $root.noteContent"></textarea>
            <p data-bind="text: $root.characterCounter"></p>
            <button class="btn btn-info" data-bind="click: $root.saveNotes">Save</button>
            <div data-bind="html: $root.status">

            </div>   
        </div>
    </div>

这个JavaScript使用淘汰赛:

var notesViewModel = function () { 
    var self = this;
    self.notes = ko.observable(null);
    self.chosenNote = ko.observable();
    self.allNotes = new Array();
    self.user = "user1";
    // behaviours
    self.goToNote = function (noteIndex) {
        self.notes(null);
        self.chosenNote(new note(self.allNotes[noteIndex]));
    };
    self.toNotes = function () {
        self.chosenNote(null);
        self.notes({ allNotes: $.map(self.allNotes, function (item) { return new note(item); }) });
        console.log(self.notes());
    }

    self.noteContent = ko.observable();
    self.saveNotes = function () {
        var request = $.ajax({
            url: "EnquiryManagement/Contact/SaveNotes",
            type: "GET",
            dataType: "json",
            data: { id: "1322dsa142d2131we2", content: self.noteContent() }
        });
        request.done(function (result, message) {
            var mess = "";
            var err = false;
            var imgSrc = "";
            if (message = "success") {
                if (result.success) {
                    mess = "Successfully Updated";
                    imgSrc = "/images/tick.png";
                    self.allNotes.push({ date: new Date().toUTCString(), content: self.noteContent(), logged: self.user });
                    self.toNotes();
                } else {
                    mess = "Server Error";
                    imgSrc = "/images/redcross.png";
                    err = true;
                }
            } else {
                mess = "Ajax Client Error";
                imgSrc = "/images/redcross.png";
                err = true;
            }

            self.status(CRTBL.CreateMessageOutput(err, mess, imgSrc));
            self.noteContent(null);
            setTimeout(function () {
                self.status(null);
            }, 4000);
        });
    };
    self.status = ko.observable();

    self.characterCounter = ko.computed(function () {
        return self.noteContent() == undefined ? 0 : self.noteContent().length;
    });
};

var note = function (data) {
    var self = this;
    console.log(data.date);
    self.date = CRTBL.FormatIsoDate(data.date);
    self.content = data.content;
    self.compressedContent = data.content == null ? "" : data.content.length < 25 ? data.content : data.content.substring(0, 25) + " ...";
    self.logged = data.logged;
    console.log(this);
};

ko.applyBindings(new notesViewModel());

当我第一次加载页面时,它说:

  

未捕获错误:无法解析绑定。   消息:ReferenceError:未定义注释;   绑定值:with:notes

但是,我将其传递为null,因此它不应该显示任何内容,因为当我执行函数goToNote然后执行goToNotes时,它会将notes observable设置为{{1} }

那么为什么我不能从这个null值开始呢?

2 个答案:

答案 0 :(得分:2)

问题在于:

<div data-bind="with: notesViewModel">

这使得它在您的notesViewModel中寻找属性“notesViewModel”,该属性不存在。

如果您只有一个视图模型,则可以删除该数据绑定,它将正常工作。

但是,如果您希望将视图模型专门应用于该div而不是整个页面,请为其提供ID或其他形式的访问者,并将其作为applyBindings中的第二个参数添加,如下所示: / p>

HTML:

<div id="myDiv">

JS:

ko.applyBindings(new notesViewModel(), document.getElementById('myDiv'));

通常只有在同一页面中有多个视图模型时才需要这样做。

答案 1 :(得分:0)

就像bcmcfc所说的那样,由于我的场景是一个多视图模型场景,我不认为他的解决方案是正确的。

为了获得正确的结果,首先我将self.notes = ko.observable(null);外推到一个viewModel中,这使得表绑定变得更加容易。

然后修复绑定问题而不是设置绑定发生的元素,我只是这样做了:

ko.applyBindings({
    mainViewModel: new mainViewModel(),
    notesViewModel: new notesViewModel()
});

在我的原始代码中,我有两个viewModel,这就是我收到此错误的原因。使用这种方法,关键是:

  

我不创建依赖性!

而不是将viewModel绑定到某个dom元素,这个元素可以很容易地改变并导致必须用ko改变一些东西,加上如果我添加更多的viewModel那么它会变得更复杂。我只是这样做:

data-bind="with: viewModel"

这样我可以绑定到任何DOM对象,并且我可以拥有许多我喜欢的对象。

这是解决我职位的解决方案。

以下是jsfiddle