Mike Wills
Mike Wills

Reputation: 21275

Knockout Click event not working

I am working on a weather page for myself (and maybe others in the future) and having an issue with a button that will show and hide weather alerts. You can view the page to see what I'm trying to do. (Sorry, I'm picking on FL, but they have a lot of alerts right now).

Page Source

JS Source

I have my alerts coming into an array and for each item, I need a button that will show and hide the alerts. My page source contains:

<div data-bind="foreach: alertsViewModel.features">
    <div class="col-12">
        <div class="alert alert-danger" role="alert">
            <p>
                <strong data-bind="text: properties.headline"></strong>
                <button type="button" class="btn btn-link" data-bind="click: $root.showHideAlert">Show</button>
            </p>
            <div data-bind="attr: {id: properties.id}" style="display: none;">
                <p data-bind="lineBreaks: properties.description"></p>
                <p><strong>Instructions</strong></p>
                <p data-bind="lineBreaks: properties.instruction"></p>
            </div>
        </div>
    </div>
</div>

And my ViewModel looks like:

// ==================
// Alerts View Model
// ==================
var alertsViewModel = {

    features: ko.observableArray([]),
    hwoUrl: ko.observable(""),
    hwoText: ko.observable(""),
    showHideAlert: function(data, event){
        alert('you clicked');
        /*$('#hwo').toggle('slow',function(){
            if ($('#showHwo').text() == "Show")
            {
                $('#showHwo').text("Hide");
            } 
            else 
            {
                $('#showHwo').text("Show");
            }
        });*/
    }
};

ko.applyBindings(weatherViewModel, document.getElementById('weather-alerts'));

I have tried a few different methods and I can't get anything to work. (Thus the commented code and the alert). Which is strange, since I have done this a few times in the past with no issues. I'm sure it's something simple I missed. Any help would be appreciated.

Upvotes: 2

Views: 1198

Answers (1)

Alucardz
Alucardz

Reputation: 548

Could it perhaps be because you used the weatherViewModel in your call to ko.applyBindings instead of alertsViewModel?

I think the $root in the button's bindings refers to weatherViewModel since that's the VM applied by ko.

Perhaps try changing the location of the function or simply use alertViewModel instead.

Upvotes: 2

Related Questions