tausch86
tausch86

Reputation: 103

Widget code that allows for javascript event callbacks

I'm creating a web application for submitting polls and whatnot. I have developed some widget code that, when a <div class = "desiredClass"> is present, a poll is fetched from the database via ajax request and is put into the html and users can vote on the poll.

so for my widget.js file that gets embedded into the html as a script:

$(document).ready(function () {
  if ($('.loadPoll')[0]) {


    var name = $('.loadPoll').data("pollname");
    var IP_Address = '-1';
    $.ajax({
      url: 'http://url.com:3000/loadPoll',
      dataType: 'jsonp',
      data: {
        pollName: name
      },
      success: function (data) {
        poll = data.poll;
        $(".loadPoll").html(data.html);
        $(document).on('click', '#SubmitVote', function () {
          var selectedValue;
          var radios = document.getElementsByTagName('input');
          for (var i = 0; i < radios.length; i++) {
            if (radios[i].type === 'radio' && radios[i].checked) {
              selectedValue = radios[i].value;
            }
          }
          console.log(selectedValue);
          $.getJSON("http://jsonip.appspot.com?callback=?", function (data) {
            var IP_Address = data.ip;

            $.ajax({
              url: 'http://url.com:3000/submitVote',
              dataType: 'jsonp',
              data: {
                pollName: poll.pollName,
                voterID: IP_Address,
                vote: selectedValue
              },
              success: callback("Vote successful")

            });
          });
        });
      }
    });
  })

This basically sends a request to the server, html is returned, then, when #SubmitVote is clicked the value of the radio button is sent to the server as a vote.

I want to be able to "allow for javascript event callbacks". Pseudocode example:

Poll.onSubmit(function() {
        console.log('hello world');
    });

How would one do this?

Upvotes: 0

Views: 83

Answers (1)

Andrew Walters
Andrew Walters

Reputation: 4803

To use the dot notation like you have there you'd want a function called Poll in your javascript.

function Poll()
{
    var self = this;
    //various things poll's do

    self.onSubmit = function(callback)
    {
        //Submit Code

        if (callback && typeof(callback) === "function") {  
              callback();  
       }  

    }

}

Then somewhere make a new Poll object.

var poll = new Poll();

Then you could call onSubmit and pass a callback.

poll.onSubmit(function() {
        console.log('hello world');
    });

Upvotes: 1

Related Questions