1

I have a form that contains a Yes/No drop-down. If "yes" is chosen, I want to use a template to generate n number of new sibling containers of html. I don't want to clutter up the html, with empty forms if they're never going to select "yes".

I'm wondering how to do this.

Perhaps I can create the containing property as an observableArray(). Then, what?, a custom binding on the select-box that runs a function that checks the value of the select box and, if "yes", grabs the array of content and $.each() observableArray.push()?

Is there a non-custom binding way to do this?

Thanks.

4

1 回答 1

0

Sure, you can do this by manually subscribing a function to your knockout observable. Your view model might look like this:

var myModel = function(){
    var self = this;
    self.buildItems = ko.observable(false);//for the yes/no
    self.items = ko.observableArray();

    //ask knockout to run this function when the buildItems observable value changes
    self.subscription = this.buildItems.subscribe(function(newValue){
        if(newValue == 'true'){
            //modify the items observableArray so that the UI is updated
            var newItems = [{name:'item1'},{name:'item2'}];
            self.items(newItems);
        }
    });
};

var model = new myModel();

and then your template may look something like this:

<div id="bindContainer">
    <select data-bind="value: buildItems">
        <option value="false">No</option>
        <option value="true">Yes</option>
    </select>
    <ul data-bind="foreach: items">
        <li data-bind="text: name"></li>
    </ul>
</div>

Here's a fiddle of this approach : http://jsfiddle.net/vmebt/

于 2013-05-25T15:40:29.980 回答