kamranayub / UnderscoreKO

A tiny library that adds all of the Underscore.js collection/array methods to Knockout observable arrays
MIT License
50 stars 11 forks source link

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

Closed kamranayub closed 8 years ago

kamranayub commented 11 years ago

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.

Nesse commented 11 years ago

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>
kamranayub commented 11 years ago

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;
    });
Nesse commented 11 years ago

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>
kamranayub commented 11 years ago

Yes, it should work

kamranayub commented 8 years ago

The newest version resolves this issue :)

kamranayub commented 8 years ago

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