我在使用 computedObservable 时遇到问题。它们看起来很简单,但我认为我的用例可能有点奇怪。问题是当 onBottom() 被调用时,它看不到 container.slides() 数组中的项目。相反,我得到“未定义不是函数”。

由于 onTop() 工作正常,这让我认为是 SlideFeaturedContent 之间的关系导致了问题,但我认为它应该可以正常工作。这里的任何帮助将不胜感激。

HTML

        <div class="section-block" data-bind="foreach: slides">
            <div class="row well">
                <div class='control'>
                    <a href='#' data-bind="click: moveUp, ifnot: onTop">
                        <i class="fa fa-arrow-up"></i>
                    </a>
                    <a href='#' data-bind="click: moveDown, ifnot: onBottom">
                        <i class="fa fa-arrow-down"></i>
                    </a>
                    <span class='pull-right'>Remove</span>
                </div>
                <h5 data-bind="text: headline"></h5>
                <p data-bind="text: image"></p>
            </div>
        </div>

JS
var FeaturedContent = function() {
    var self = this;

    self.maxSlides = 14;
    self.slides = ko.observableArray([
        new Slide({}, "I should be last", "someimg", 0, self),
        new Slide({}, "I should be first", "anotherimg", 1, self),
        new Slide({}, "I should be second-", "anotherimg", 2, self),
    ]);

    // ... snipped.

};

var Slide = function(contentItem, headline, image, order, container) {
    var self = this;

    // -- Data
    self.contentItem = contentItem;
    self.headline = headline;
    self.image = image;
    self.position = ko.observable(0);

    self.onBottom = ko.computed(function() {
        return (self.position() === container.slides().length - 1) ? true : false;
    });

    self.onTop = ko.computed(function() {
        return (self.position() === 0) ? true : false;
    });

    return self;
};

最佳答案

创作过程中

self.slides = ko.observableArray([
    new Slide({}, "I should be last", "someimg", 0, self),
    new Slide({}, "I should be first", "anotherimg", 1, self),
    new Slide({}, "I should be second-", "anotherimg", 2, self),
]);

FeaturedContent 您的代码将创建 new Slide 并使用 self 获取 container.slides().lengthselfcontainerslides() 尚未创建。这是一个圆引用。所以 container.slides() 是未定义的。

试试这样的 container.slides() && self.position() === container.slides().length - 1

10-07 21:30