omer
omer

Reputation: 2623

Trying to avoid the use of $watch

The code snippet below alters a DOM element when the element is smaller than 700px width. My question is, how can I do the same thing without using a watcher?

$scope.$watch(function () {
                    return $('#calendar').width();
                }, function () {
                    if ($('#calendar').width() < 700) {
                        $('#calendar').fullCalendar('changeView', 'agendaDay');
                    }
                });

Upvotes: 1

Views: 75

Answers (2)

Endre Simo
Endre Simo

Reputation: 11551

You can obtain the same effect with eventListener.

Something like this:

function checkWindowWidth () {
    if ($window.innerWidth < 700)
        $('#calendar').fullCalendar('changeView', 'agendaDay');    
    $scope.$apply();
};

window.addEventListener('resize', checkWindowWidth);
window.addEventListener('load', checkWindowWidth); // or check on load

If you are using underscore, it has a good utility function for debounce, and it's recommended to use a debounce function on resize.

var checkWindowWidth = _.debounce(function() {
    if ($window.innerWidth < 700)
        $('#calendar').fullCalendar('changeView', 'agendaDay');    
    $scope.$apply();
}, 10, true);

window.addEventListener('resize', checkWindowWidth);
window.addEventListener('load', checkWindowWidth); // or check on load

Upvotes: 0

Daniel
Daniel

Reputation: 3514

As you are already using jQuery you might use the resize() method:

$("#calendar").resize(function(){
    if ($(this).width() < 700) {
        $(this).fullCalendar('changeView', 'agendaDay');
    }
});

You might additionally need to execute the same code on initial load of your div.

Upvotes: 1

Related Questions