2
votes

What I want to achieve is create a custom binding for Knockout.js which enables to bind to model and play defined audio file using HTML5 audio tag when that observable changes. so for example it would look something like

<p data-bind="audio: {value: someobservable, sound:'pathto/sound.mp3'}"><?p>

as far as I understand this must bu custom knockout binding which has init and update methods and on init it checks if any audio tag is presented in DOM and create one in case there is no audio tag and play sound value in case value property changes. as far as I understand I must internally subscribe to value binding but could not get exact idea how to implement that. could anyone help me out there?

1
Have you read the Knockout documentation about creating a custom binding? It contains samples you can look at. Also, please edit your question and add what you have tried and what errors you get in your attempts. - Robert Westerlund
sure i did i created a lots of bindings before that the only problem was related with audio binding. I am not asking for code all I want is direction or some hints about how to work with html5 audio? should i use jQuery for that? - Rati_Ge
Why do you want to create a the audio tag dynamically? Why don't you just create a custom binding which you put on an existing audio tag which plays the file when the observable changes? - nemesv

1 Answers

1
votes

You don't need to create an audio tag, you can just use the JavaScript audio API to play a sound if the observable changes:

ko.bindingHandlers.audio = {
    init: function (element, valueAccessor) {
        var config = ko.unwrap(valueAccessor());
        var file = config.sound;
        var observable = config.value;
        observable.subscribe(function () {
            var audio = new Audio(file);
            audio.play();
        });
    }
};

And you can use it as in your question:

<p data-bind="audio: {value: someobservable, 
                 sound:'http://www.w3schools.com/TAGs/horse.ogg'}">SOme test</p>

Demo JSFiddle.