kamranayub / UnderscoreKO

A tiny library that adds all of the Underscore.js collection/array methods to Knockout observable arrays

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`_.where` doesn't work when items in array are observable

kamranayub opened this issue · comments

From Google Groups:

The following code is from underscore.js this code never finds a match b/c value[key] is an observable object. If I change the code to value[key]() then the where works as you'd expect.

_.where = function(obj, attrs, first) {
    if (_.isEmpty(attrs)) return first ? void 0 : [];
    return _[first ? 'find' : 'filter'](obj, function(value) {
      for (var key in attrs) {
        if (attrs[key] !== value[key]) return false;
      }
      return true;
    });

UKO should make this compatible by using ko.util.unwrapObservable.

Hey kamranayub.

I love your library, but was struggling with the where statement until i found this issue. Is this bug fixed in the latest build? I don't want to change the underscore library because i use nuget to pull the latest updates, and will forget about this. Is there another method achieving this:

<ol data-bind="template: { name: 'nested-template', foreach: Categories.where({ ParentCategoryId: null }) }" class="dd-list">
</ol>

I'd like to find a way while avoiding duplicating the Underscore code, but worse comes to worse, you can just declare this after loading Underscore and my lib:

ko.observableArray.fn.where = function(obj, attrs, first) {
    if (_.isEmpty(attrs)) return first ? void 0 : [];
    return _[first ? 'find' : 'filter'](obj, function(value) {
      for (var key in attrs) {
        if (attrs[key] !== ko.util.unwrapObservable(value[key])) return false;
      }
      return true;
    });

Thx for your response. Can i use your code in the html with knockout like this?

<ol data-bind="template: { name: 'nested-template', foreach: Categories.where({ ParentCategoryId: null }) }" class="dd-list">
</ol>

Yes, it should work

The newest version resolves this issue :)

Just pushed a fix that also supports arrays where the items are view models themselves and contain observables.