Ограничение и сортировка элементов knockout.js по каждому элементу

Я действительно новичок в knockout.js. то, что я пытаюсь достичь, ограничивает каждый элемент. вот это мой источник:

<div data-bind="foreach: news">
      <!-- ko if: catId === '4' -->
            <div  class="news-item">
                <a data-bind="attr: { href: url, title: title }">
                   <div class="news-header-text" data-bind="text: title"></div>
                 </a>
                 <div class="news-date" data-bind="text: date" /></div>

            </div>
      <!-- /ko -->
</div>

это мой javascript:

 (function()
        { // Wrap in function to prevent accidental globals
            if(location.protocol != "data:")
            {
                $(window).bind('hashchange', function()
                {
                    window.parent.handleChildIframeUrlChange(location.hash)
                });
            }

            // Class to represent a row in the seat reservations grid
            function cebesEnNewsIndex(title, date, url, catId, hits)
            {
                var self = this;
                self.title = title;
                self.date = date;
                self.url = url;
                self.catId = catId;
                self.hits = hits;
            }

            // Overall viewmodel for this screen, along with initial state
            function cebesEnNewsIndexViewModel()
            {
                var self = this;


                // Non-editable catalog data - would come from the server

                // Editable data
                self.news = ko.observableArray([
                new cebesEnNewsIndex("Welcome to Cebes Enterprise", "18 Mey 2012", "#", '4', '20'),
                new cebesEnNewsIndex("Groove for Dummies", "20 Mey 2012", "#", "4", "21"),
                new cebesEnNewsIndex("New Features of Cebes Framework", "18 Mey 2012", "#", "3", "19"),
                new cebesEnNewsIndex("Welcome to Cebes Enterprise", "20 Mey 2012", "#", "3", "24"),
                new cebesEnNewsIndex("Welcome to Cebes Enterprise sdfadfa", "18 Mey 2012", "#", '4', '20'),
                new cebesEnNewsIndex("Groove for Dummiessdfadf", "20 Mey 2012", "#", "4", "21"),
                new cebesEnNewsIndex("New Features of Cebes Frameworksdfad", "18 Mey 2012", "#", "3", "19"),
                new cebesEnNewsIndex("Welcome to Cebes Enterprisdfadfe", "20 Mey 2012", "#", "3", "24"),
                new cebesEnNewsIndex("Welcome to Cebes Enterprissdfadfe", "18 Mey 2012", "#", '4', '20'),
                new cebesEnNewsIndex("Groove for Dummiesdfads", "20 Mey 2012", "#", "4", "21"),
                new cebesEnNewsIndex("New Features of Cebes Framework", "18 Mey 2012", "#", "3", "19"),
                new cebesEnNewsIndex("Welcome to Cebesasdfa Enterprise", "20 Mey 2012", "#", "3", "24"),
                new cebesEnNewsIndex("Welcome to Cebessdfad Enterprise", "18 Mey 2012", "#", '4', '20'),
                new cebesEnNewsIndex("Groove fsdfaor Dummies", "20 Mey 2012", "#", "4", "21"),
                new cebesEnNewsIndex("New Featuresadfas of Cebes Framework", "18 Mey 2012", "#", "3", "19"),
                new cebesEnNewsIndex("Welcome tosdfad Cebes Enterprise", "20 Mey 2012", "#", "3", "24"),
                new cebesEnNewsIndex("New Emsfadfployee", "22 Mey 2012", "#", "5", "25")
                ]);


            }


            ko.applyBindings(new cebesEnNewsIndexViewModel());
        })();

как вы можете видеть на скрипте, фильтрация работает и отображает 8 новостей

Я хочу ограничить число и отсортировать число на основе элементов дат с одинаковыми данными, которые становятся такими (отображение только 3 отфильтрованных и отсортированных новостей):

http://jsfiddle.net/2Ffqn/

вот ссылка jsfiddle моего скрипта: http://jsfiddle.net/StRa6/, чтобы было проще и пожалуйста, отредактируйте и сохраните мой jsfiddle. любые предложения приветствуются.

Спасибо.


person user1097182    schedule 31.07.2012    source источник


Ответы (1)


Вы не должны помещать бизнес-логику в такое представление. Гораздо лучшим решением было бы создать отфильтрованный массив с использованием наблюдаемого computed и привязать к нему.

self.selectedNews = ko.computed(function() {
    return ko.utils.arrayFilter(self.news(), function(i) {
         return i.catId == 4; //Or, you know, whatever
       })
    });

Вот скрипка.

person Kyeotic    schedule 31.07.2012
comment
Спасибо Tyrius за совет, но вы еще не показали мне, как ограничить цикл foreach указанным числом. - person user1097182; 31.07.2012
comment
Гм. да. Да. Посмотри на скрипку. Отображаются только элементы с catId == 4, как на вашем экзамене. Если это не то, что вы хотели, опубликуйте пример желаемого результата. - person Kyeotic; 31.07.2012
comment
Вы просто полностью изменили свой вопрос. - person Kyeotic; 31.07.2012