user3131689
user3131689

Reputation: 1

Knockout databinding

when I click the link it works great, when, I use the showModal click event, I get three open modals on page load (three items in the list) and when I click a button, I get three modals. I would like to use a modal as the list is in another page view. I think I just need some help with the data binding to event model.

<div class='liveExample'>
        <table >
            <tr data-bind="foreach: items">
                <td data-bind="text:ID"></td>
                <td data-bind="text:Title"></td>
                <td data-bind="text:Body"></td>
                <td data-bind="text:Expires"></td>
               <!-- <td> <button data-bind="click: showModal(Title, Url )">Edit</button> </td>-->
                <td><a data-bind="attr: { href: Url }">Edit</a></td>
            </tr>

        </table>

    </div>

ShowModal is a standard JavaScript function (SharePoint) not part of the View Model.

Upvotes: 0

Views: 111

Answers (2)

Captain John
Captain John

Reputation: 2001

The problem with the above is that you are putting code in your view.

In some cases this works well. However when you have designers using your code and potentially re-ordering things etc. functions in the view can get lost.

Suggest a similar approach:

<td data-bind="text:Expires"></td>
<td>
    <button data-bind="click: showModalEvent">Edit</button>
</td>

In the viewModel

showModalEvent : function(data, e) {
    showModal(data.Title, data.Url);
}

Then you can run static analysis etc more easily on your code to catch changes errors etc and keep your view nice and simple.

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134581

When using the click binding, you are binding to a function to be called when clicked. However, you are not providing the function to call in your binding, but actually calling the function instead. You need to wrap that into a function to be called when clicked on.

You need to do something like this:

<div class='liveExample'>
    <table >
        <tr data-bind="foreach: items">
            <td data-bind="text:ID"></td>
            <td data-bind="text:Title"></td>
            <td data-bind="text:Body"></td>
            <td data-bind="text:Expires"></td>
            <td>
                <button data-bind="click: function () { showModal(Title, Url ); }">Edit</button>
            </td>
            <td>
                <a data-bind="attr: { href: Url }">Edit</a>
            </td>
        </tr>
    </table>
</div>

Upvotes: 1

Related Questions