Frage

I'm trying to write a script that once a button is presses it will display the duration of a song from SoundCloud. I'm also having a little trouble with the APIs. I've read and reread the line about some "callback" passed a parameter but i still do not understand. "Because of this, every getter method accepts a callback function as a parameter which, when called, will be given the return value of the getter method."

Here is where i'm at with my code. I know its not pretty but i'm just trying to make the darn thing work.

<!doctype html>
    <html>
    <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
      <script src="http://w.soundcloud.com/player/api.js"></script>
      <script>
       $(document).ready(function() {
         var widget = SC.Widget(document.getElementById('playing'));
         widget.bind(SC.Widget.Events.READY, function() {
           console.log('Ready...');
         });

         $('button').click(function() {
           widget.getDuration(function(sound));
         });
       });

       function sound(var time) {
        document.write(time);
       }
      </script>
    </head>
    <body>
                <iframe id="playing" 
                width="500" 
                height="400" scrolling="no" 
                frameborder="yes" 
                src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/66816173&amp;auto_play=false&amp;hide_related=false&amp;visual=true">
                </iframe>
      <button>Play / Pause</button>
    </body>
    </html>
War es hilfreich?

Lösung

There are two wrong function definitions in your code. On developer.mozilla.org you can find some very good javascript documentation. In particular, on this page, you can learn how to properly define functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Back to your code:

1) The getDuration soundcloud function accepts a callback. function(sound) is not a valid function definition.

2) A function definition does not need the var keyword before the argument name

Here is your code with the two corrections. It works as you might expect.

var widget = SC.Widget(document.getElementById('playing'));
    widget.bind(SC.Widget.Events.READY, function() {
        console.log('Ready...');
    });

    $('button').click(function() {
        widget.getDuration(function(duration){
            alert(duration);
        });
    });
});

and here you can see the working fiddle: http://jsfiddle.net/Ldc2N/

One more thing: I see that in what was supposed to be the callback, you call document.write.

function sound(time) { document.write(time); }

Please consider that it only appends content to the document when it is not ready, yet. Calling int when the document is ready completely overwrites its content.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top