0

I got these two ko.computeds lists that I want to drag and drop among, but also moved with pushbuttons to remove an add to lists.

However I cannot make them work with both the dragndrop and the pushbutton functionality.

For the drag and drop I use Ryan Niemeyers excellent sortable library.

I guess I need to make my computeds writable, but this is where I get stuck and can´t seem to get rid of the error "splice is not a function" for the computed.

Hence the sorting by drag and drops fails.

This is one of the computers:

         this.availableTexts = ko.computed({
            read: function(){
               return ko.utils.arrayFilter(self.texts(), function(text) {
               return text.sceneID() === null;
            })
          },
          write: function(value){
            return value;
          },
          owner: this
        });

Full fiddle: http://jsfiddle.net/AsleG/yLvrp7zz/

Asle G
  • 568
  • 7
  • 27

2 Answers2

1

Niemeyer's knockout-sortable library works with splice internally to sort an array of items (source). I believe it simply won't work on a computed, even if it returns an array and has a correct write method...

I'd suggest to use the visible binding to hide individual items. You'll have to expose projectID or map your items to include a computed like so:

var projectID = 1;
self.allScenes = ko.observableArray(scenes.map(function(scene) {
  return Object.assign({}, scene, {
    isVisible: ko.computed(function() { 
      return scene.projectID === projectID;
  });
});

Alternatively, in viewmodel:

self.projectId = 1;

in HTML:

<li data-bind="visible: projectID === $parent.projectId"> ... </li>
user3297291
  • 22,592
  • 4
  • 29
  • 45
  • That´s a very good suggestion for a workaround, @user3297291. However I get back to the fact that the texts I am binding against "visible" statement still is a computed since it is filtered on projectID. I could of course add the projectID to the visible, but that would potentially load lots of text in my view. Surely there must be a way to work around this with subscribe-function? – Asle G Jun 29 '16 at 18:17
  • 1
    You may use `if` binding on virtual element instead of `visible` (`
  • ...
  • `. And elements inside `if` will be excluded from DOM and processing in the right case. – Tarwirdur Turon Jun 29 '16 at 21:54