KnockoutJS清除函数内的Observable

时间:2015-03-24 12:05:13

标签: javascript knockout.js

我的剃刀视图如下:

<div id="allMessages" data-bind="foreach: messages">
    <!-- ko if: $root.filterMessageTime($data.MessageDate) -->
           //Show some messages
    <!-- /ko -->
</div>
<div data-bind="visible: lastHourCount() > 1 && selectedFilterMessageTime() == 'Last Hour'">
    <p><span class="h4" data-bind="text: lastHourCount()"></span> messages in the <span class="h4">last hour</span>.</p>
</div>
<div data-bind="visible: lastHourCount() == 0 && selectedFilterMessageTime() == 'Last Hour'">
    <p>No new messages in the <span class="h4">last hour</span>.</p>
</div>

我的Knockout功能如下:

function ViewModel() {
    var self = this;
    var count = 0;

    self.lastHourCount = ko.observable(0);
    self.lastDayCount = ko.observable(0);
    self.lastWeekCount = ko.observable(0);
    self.lastMonthCount = ko.observable(0);

    self.filterMessageTime = function (MessageDate) {
        //Reset Expression
        if (count == self.messages().length) {
            count = 0;
            self.lastHourCount(0);
            self.lastDayCount(0);
            self.lastWeekCount(0);
            self.lastMonthCount(0);
        }
        if (self.selectedFilterMessageTime() == 'Any' || self.selectedFilterMessageTime() == null) {
            return true;
        }
        count = count + 1;
        if (self.selectedFilterMessageTime() == 'Last Hour') {
            if (((MessageDate.indexOf('minute') >= 0) || (MessageDate.indexOf('hour') >= 0)) && (MessageDate.indexOf('hours') == -1)) {
                self.lastHourCount(self.lastHourCount() + 1);
                return true;
            }
            else
                return false;
        }
        else if (self.selectedFilterMessageTime() == 'Last Day') {
            if (((MessageDate.indexOf('day') >= 0) || (MessageDate.indexOf('hours') >= 0) || (MessageDate.indexOf('hour') >= 0) || (MessageDate.indexOf('minute') >= 0)) && (MessageDate.indexOf('days') == -1)) {
                self.lastDayCount(self.lastDayCount() + 1);
                return true;
            }
            else
                return false;
        }
        else if (self.selectedFilterMessageTime() == 'Last Week') {
            if ((MessageDate.indexOf('days') >= 0) || (MessageDate.indexOf('day') >= 0) || (MessageDate.indexOf('hours') >= 0) || (MessageDate.indexOf('hour') >= 0) || (MessageDate.indexOf('minute') >= 0)) {
                self.lastWeekCount(self.lastWeekCount() + 1);
                return true;
            }
        else
                return false;
        }
        else if (self.selectedFilterMessageTime() == 'Last Month') {
            if ((MessageDate.indexOf('month') >= 0) || (MessageDate.indexOf('days') >= 0) || (MessageDate.indexOf('day') >= 0) || (MessageDate.indexOf('hours') >= 0) || (MessageDate.indexOf('hour') >= 0) || (MessageDate.indexOf('minute') >= 0)) {
                self.lastMonthCount(self.lastMonthCount() + 1);
                return true;
            }
            else
                return false;
        }
        return false;
    };
}

方法:

对于我拥有的每条用户消息,如果用户指定过滤器,则:

  1. 根据传入的MessageDate计算该过滤器范围内的邮件数量,并将其显示在可观察对象中,即self.lastMonthCount()将保留上个月的邮件数量
  2. count达到消息总数时,我们希望重置计数以及可观察计数器,以便可观察计数不会翻转任何值。
  3. 问题:

    似乎我对我的observable有一些形式的循环依赖,因为在运行函数时存在问题,即'reset'表达式从未正确评估,似乎函数循环的数量很大(大于Observables中的消息量。

    注意:

    • 用常规变量替换observable时一切正常,自然我在视图中没有数据绑定这是不好的。
    • 如果我在重置表达式中重新声明我的Observables然后它解决了我的问题,但是我之前绑定的Observables将不再从新创建的Observables接收更新,再次没有好处。
    • 我还尝试将Observable设置为nullundefinied

1 个答案:

答案 0 :(得分:2)

你这样做是错误的。

如果您有一个包含对象列表的视图模型,并且您想让它们可过滤,那么您需要做的就是

  • 添加一个包含有效过滤条件的observable
  • 添加一个包含已过滤列表的计算
  • 将您的观点完全建立在已过滤的列表

其余的将自然而然。

function ViewModel() {
    var self = this;

    self.availableFilters = ['any', 'last hour', 'last day', 'last week', 'last month'];
    self.activeFilter = ko.observable(self.availableFilters[0]);
    self.allMessages = ko.observableArray([/* ... fill this ... */]);

    self.filteredMessages = ko.pureComputed(function () {
        return self.filterMessages(self.activeFilter());
    });
    self.filteredMessagesCount = ko.pureComputed(function () {
        return self.filteredMessages().length;
    });

    self.filterMessages = function (filter) {
        return ko.utils.arrayFilter(self.allMessages(), function (message) {
            var d = message.Date();
            switch (filter) {
                case 'any':        return true;
                case 'last hour':  return (d.indexOf('minute') >= 0 || d.indexOf('hour') >= 0) && d.indexOf('hours') == -1;
                case 'last day':   return (d.indexOf('day') >= 0 || d.indexOf('hours') >= 0 || d.indexOf('hour') >= 0 || d.indexOf('minute') >= 0) && d.indexOf('days') == -1;
                case 'last week':  return d.indexOf('days') >= 0 || d.indexOf('day') >= 0 || d.indexOf('hours') >= 0 || d.indexOf('hour') >= 0 || d.indexOf('minute') >= 0;
                case 'last month': return d.indexOf('month') >= 0 || d.indexOf('days') >= 0 || d.indexOf('day') >= 0 || d.indexOf('hours') >= 0 || d.indexOf('hour') >= 0 || d.indexOf('minute') >= 0;
                default:           return false;
            }
        });
    };
}

<select data-bind="options: availableFilters, value: activeFilter"></select>

<div id="allMessages" data-bind="foreach: filteredMessages">
    // show the message
</div>
<div>
    <p>
        <!-- ko if: filteredMessagesCount -->
        <span class="h4" data-bind="text: filteredMessagesCount"></span> messages
        <!-- /ko -->

        <!-- ko ifnot: filteredMessagesCount -->
        No new messages
        <!-- /ko -->

        <!-- ko ifnot: activeFilter() === 'any' -->
        in the <span class="h4" data-bind="text: activeFilter"></span>
        <!-- /ko -->
    </p>
</div>

话虽如此,您过滤消息的方法(通过多个indexOf()调用)并不是很漂亮。

基于正则表达式的那个:

function ViewModel() {
    var self = this;

    self.availableFilters = [
        {name: 'any',        include: /./, exclude: null},
        {name: 'last hour',  include: /minutes?|hour/i,  exclude: /hours|days?|weeks?|months?/i},
        {name: 'last day',   include: /minutes?|hours?|day/i,   exclude: /days|weeks?|months?/i},
        {name: 'last week',  include: /minutes?|hours?|days?|week/i,  exclude: /weeks|months?/i},
        {name: 'last month', include: /minutes?|hours?|days?|weeks?|month/i, exclude: /months/i}
    ];
    self.activeFilter = ko.observable(self.availableFilters[0]);
    self.allMessages = ko.observableArray([/* ... fill this ... */]);

    self.filteredMessages = ko.pureComputed(function () {
        return self.filterMessages(self.activeFilter());
    });
    self.filteredMessagesCount = ko.pureComputed(function () {
        return self.filteredMessages().length;
    });

    self.filterMessages = function (filter) {
        return ko.utils.arrayFilter(self.allMessages(), function (message) {
            var d = message.Date();
            return filter.include && filter.include.test(d) &&
                   !(filter.exclude && filter.exclude.test(d));
        });
    };
}

<select 
    data-bind="options: availableFilters, optionsText: 'name', value: activeFilter"
></select>

视图的其余部分是相同的,只是对activeFilter()的引用必须更改为activeFilter().name