簡體   English   中英

Knockout通過訪問observableArray來計算observable

[英]Knockout computed observable with access to observableArray

我在使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM