• Item 1
  • Item 2
  • ...">

    Link existing HTML to view the model

    I have a page with ready HTML content that allows:

    <ul id="list">
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
    
          

    I need to link these elements in order to view the model. In other words, after the call, 'ko.applyBindings(viewModel, $('#list')[0])'

    I would like to viewModel

    get my values ​​from existing HTML. So I am doing the following:

    <ul id="list" data-bind="foreach: items">
        <li data-bind="text: title">Item 1</li>
        <li data-bind="text: title">Item 2</li>
    </ul>
    
          

    and expect to viewModel

    receive an array items

    of the above items. But as a result, the DOM is cleared.

    +3


    source to share


    1 answer


    I am assuming that you cannot just bind the html coming from the server to your view model.

    So this would mean that you are trying to reverse engineer the view model from existing HTML, you would need to traverse the DOM to get the result you are looking for.

    So, rename the list with links so that your bindings have one purpose:

    <ul id="list2" data-bind="foreach: Items">
        <li data-bind="text: title"></li>
    
          



    Then you will need to work with your original html list which you could not use to knock out and walk through it to get the values.   

        var viewModel = {
           Items= ko.observableArray();
        }
    
        //select your list
        var list = $('#list');
    
        //iterate through the children and add to the observable array
        ko.utils.arrayForEach(list.children(),function(i){
            viewModel.Items.push({Title:i.text()});
        }
    
         //then you can bind the view model to your html that has the knockout bindings
    
         ko.applyBindings(viewModel, )
    </script>
    
          

    +1


    source







    All Articles