knockout.js, knockout-sortable, and default text

273 Views Asked by At

I'm using knockout.js and knockout-sortable, and I'm currently trying to get some default text inside of the sortable parent element if there are no elements in the array passed into the sortable binding.

This is related to this stackoverflow question, but different due to my requirement: I cannot have the text outside of the parent element. Meaning, this:

<div data-bind="if: pets().length > 0">These are the pets:</div>
<div data-bind="if: pets().length == 0">There aren't any pets. To add a pet...</div>
<div data-bind="foreach: pets">

... is not valid for me. The text needs to be contained inside of the foreach loop so it also functions as a drop area. I did take a look at the knockout-punches library but I haven't come up with a solution using it yet. I'm open to a pure knockout solution or a plugin.

My code currently looks like this:

<div class="my-drop" data-bind="foreach: { template: 'myTemplate', data: myContainerList}"></div>
2

There are 2 best solutions below

1
On BEST ANSWER

You can create a new binding or extend foreach to show something when the array is empty. Here's an example that extends foreach.

var origForeachUpdate = ko.bindingHandlers.foreach.update;
ko.bindingHandlers.foreach.update = function(element, valueAccessor) {
    var options = valueAccessor();
    if (options.defaultText) {
        var array = ko.unwrap(options.data);
        if (!array || !array.length) {
            element.innerText = options.defaultText;
        } else if (element.innerText == options.defaultText) {
            element.innerText = "";
        }
    }
    origForeachUpdate.apply(this, arguments);
};

http://jsfiddle.net/mbest/Z7BeM/

3
On

Use a virtual-element binding:

<div>
<span data-bind="if: pets().length > 0">These are the pets:</span>
<span data-bind="if: pets().length == 0">There aren't any pets. To add a pet...</span>
<!-- ko foreach: pets -->
<!-- /ko -->
</div>

Virtual bindings are the standard way to handle the case where you need a list that includes some fixed items as well as variable items.