无法使用Knockout从REST绑定或呈现富文本

时间:2014-07-26 20:25:37

标签: javascript jquery html rest knockout.js

我正在获取数据并且它确实呈现了标题,但似乎无法呈现富文本。

标记:

<div id="bodyarea">
    <div data-bind=foreach:list>
        <span data-bind="text:Title" />
        <div data-bind="html: RichData"></div>
    </div>
</div>
    <p id="myarea"></p>

KO:

function LoadLists() {
    var listItems = [];
    var count = 0;
    $.getJSON("https://myserver.com/sites/knockout/_api/lists/getbytitle('List%20One')/items?$filter=Title eq 

'zzzz'",

        function (data, textstatus, jqXHR) {

            $(data.value).each(function (index, item) {
                count++;
                var koItem = {};
                koItem.Title = item.Title;
                koItem.RichData = item.Rich;


                listItems.push(koItem);

                if (data.value.length == count) {
                    var vm =
                                    {
                                        list: ko.observableArray(listItems)
                                    };
                    ko.applyBindings(vm, document.getElementById("bodyarea"));
                }

            })
        });


}
$(document).ready(function () { LoadLists(); });

1 个答案:

答案 0 :(得分:0)

一般情况下,淘汰赛时,你不应该:

  • 多次调用applyBindings
  • 在ajax调用中调用applyBindings
  • 将viewModel创建为普通对象(通常,有时它很好)
  • 在jQuery事件处理程序中进行敲除数据绑定。

代码:

// this is a reusable view model for each item. it takes a raw item from the ajax return, and creates observables for each property.
var ListItem = function (item) {
    var self = this;
    self.Title = ko.observable(item.Title);
    self.RichData = ko.observable(item.Rich);
}

// Your viewModel. Constructor-esque syntax is pretty standard.
var ViewModel = function () {
    var self = this;

    // this is your list array.
    self.list = ko.observableArray();

    // This is a your reusable function to load lists, when it returns, it maps each item
    // in data.value to a ListItem viewModel and puts them all in the lists observableArray
    self.loadList = function() {
            $.getJSON('yourUrl', function(data) {
                var items = data.value.map(function(item) { return new ListItem(item); });
                self.list(items);
            }
    };
};

// When the document is ready, create a view model and apply bindings once. Then call loaLists to initialize
$(document).ready(function () { 
    var vm = new ViewModel();
    ko.applyBindings(vm);
    vm.loadList();
});