Sunday, September 4, 2011

Play and stop an alarm sound using HTML5 audio in a Backbone view

I'm using Backbone.js in my toy project.
I had to adapt the example in my previous post so it could be used in a backbone view.
This is how I did it:
AlarmView = Backbone.View.extend({    
    events: {
        'click #alarmButton': 'alarmButtonPressed',
    },

    initialize: function(){
        _.bindAll(this, 'render', 'alarmButtonPressed', 
                  'preSelectElements', 'playAlarm', 
                  'stopAlarm');                
        this.preSelectElements();        
        this.render();
    },

    preSelectElements : function () {
        this.alarmText = this.$('#alarmTime');
        this.alarmButton = this.$('#alarmButton');
    },

    render: function(){
        return this;
    },

    alarmButtonPressed : function() {
        this.playAlarm();
    },
    
    playAlarm : function () {    
        this.alarmSound = new Audio("alarm.wav");
        setTimeout(this.stopAlarm, this.alarmText.val() * 1000);
        this.alarmSound.play();
    },
    
    stopAlarm : function () {   
        this.alarmSound.pause();
        this.alarmSound.startTime = 0;
    },    
});

$(function(){
    var alarmView = new AlarmView({el: $(document)});
});

And this is the HTML:
<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <script src="libs/jquery-1.6.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="libs/underscore.js" type="text/javascript" charset="utf-8"></script>
        <script src="libs/backbone.js" type="text/javascript" charset="utf-8"></script>
        <script src="alarm.js" type="text/javascript" charset="utf-8"> </script>
    </head>

    <body>
        <input type="text" id="alarmTime" value="1"/>
        <button type="button" id="alarmButton">Start alarm</button>
    </body>    
</html>

No comments:

Post a Comment