0

I'm trying to get a handle on javascript and prototype (not the library) to create a reusable script that will ultimately output a nice, formatted table of data from a database. I'm able to use jQuery AJAX to get the data in JSON format, and generate the table without issue. Ideally, it'll be sortable and paged, and that's where the trouble starts.

I've tried a few methods of construction, but it seems that using javascript's prototype is what I want, if I'm understanding it correctly. What I seem to be misunderstanding (at the very least) is data persistence when the user takes action by clicking a link or a button.

Here's a short for which I've created to illustrate the issue:

http://jsfiddle.net/Scopique/yrt3krn9/

    //Uses jQuery 1.11.0 because IE

var Outside = function () {
    this.MyVariable = 'Hi';
    this.PersistVariables = 'Oops';
}

Outside.prototype.GenerateHTML = function () {
    var that = this;

    //Value pops as expected
    alert(that.PersistVariables);

    var localHTML = "<a href='#' id='link' onclick='Outside.prototype.Respond(\"" + that.MyVariable + "\");'>Click Me</a>";
    $("#output").html(localHTML);
}


Outside.prototype.Respond = function (whatVariable) {
    var that = this;

    alert(whatVariable);

    //Value does not pop...
    alert(that.PersistVariables);

}

$(document).ready(function () {
    var out = new Outside();
    out.GenerateHTML();
});

And beyond this there's just:

<div id="output"></div>

In this example, the value of MyVariable is visible when Outside.prototype.Respond is trigged through clicking the link that's added to the DIV at run time as it's being explicitly handed down through the process of definition, building the HTML, and passed as an argument to the method.

However, PersistVariables always comes back as undefined when Respond is called. It's assigned a value in the constructor, and it displays the proper value when GenerateHTML is called -- a natural execution flow, I'm supposing -- but the value isn't understood in Respond after the link has been clicked.

I could ask "what am I missing" but I suspect that it's not that simple :D Are the variables that I want to access scoped correctly? If so, what is it about the link click that causes them to lose their minds post-link click.

Thanks!

1
  • The problem with that code is that this refers to the invoking object. Invoking alert with window.alert or alert the value of this in alert will be window. Invoking Outside.prototype.Respond the value of this in Respond will be Outside.prototype not the instance of Outside. You should take care of your capitalization; constructor functions usually start with a capital but functions that are not uses as constructors don't. More info on prototype here: stackoverflow.com/a/16063711/1641941
    – HMR
    Nov 14, 2014 at 0:22

4 Answers 4

2

Your problem has to do with scope and your understanding of prototypical programming. This is a very deep subject with lots of references online so I'm not going to do a full explanation here.

Basically by adding properties to the prototype property means adding functionality to all instances of the object you are creating. When you output the html the context of the JavaScript attached to the elements is the global context so it doesn't know anything about any of the methods within the Outside prototype. What you need in this case is a global reference to your Outside instance out. Then your click handler can call out.Respond

Here is your updated Fiddle

var Outside = function() {
  this.MyVariable = 'Hi';
  this.PersistVariables = 'Oops';
}

Outside.prototype.GenerateHTML = function() {
  var that = this;

  var localHTML = "<a href='#' id='link' onclick='out.Respond(\"" + that.MyVariable + "\");'>Click Me</a>";
  $("#output").html(localHTML);
}


Outside.prototype.Respond = function(whatVariable) {
  var that = this;

  alert(whatVariable);
  alert(that.PersistVariables);
}

var out = new Outside();
$(document).ready(function() {
  //var out = new Outside();
  out.GenerateHTML();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="output"></div>

--EDIT--

MDN Prototype is most likely going to provide some of the best information.

Here are some other links that look pretty good at first glance:

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#newwindow=1&q=javascript+prototype+-site:w3schools.com

1
  • Ah! Totally understand. I switched up the approach in the real code, and it worked like a charm. Thanks for the assistance and explanation!
    – Scopique
    Nov 14, 2014 at 15:21
0

Clicking a link causes a postback which resets the scope (clears any javascript code you have loaded). This is why you have to include the <script> tags in your page because every time it loads the javascript must be loaded.

That said it is possible do do what you want.

Most browsers support an Html5 feature called Local or Web Storage Go here for more info on how to use Local Storage. It is also possible to use cookies to store small amounts of data in json format that can be accessed after a postback. And finally you can avoid doing the postback altogether by intercepting the click event and make an ajax call to get the data you want.

I hope this helps.

1
  • The question has href='#' so this answer does not apply to this particular question. When navigating between different pages on the same site this answer is valid though.
    – HMR
    Nov 14, 2014 at 0:29
0

The onClick link you are introducing is not calling the Outside instance you created earlier.

I've updated the fiddle to place the out variable in global scope and then to have it referenced in the inserted link.

http://jsfiddle.net/yrt3krn9/3/

I'd also recommend handling the event outside of the 'onClick' attribute. That is, create an event handler for the link like so:

$("#output").on("click","#link",function(e){
   //handle event
});
0

As Jared (HJ05) indicated; there is a better way to attach event on elements. Since you want to fill a certain container (element with id output) with your html and respond to only events within the container it's better to attach a click handler on that container.

Then use the event and event.target (the clicked element) together with data properties (in this case data-action) to figure out what to with the click.

Here is an example:

<!DOCTYPE html>
<html>
<head>
  <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
  </script> 
</head>
<body>
    <div id="output"></div> 
    <script>
        var Outside = function (id) {
            var me =  this;
            this.myVariable = 'Hi';
            this.PersistVariables = 'Oops';
            this.container = $("#"+id);
            this.container.on('click',function(e){
                me.clickHandler(e);
            });
        }
        Outside.prototype.generateHTML = function () {
            var localHTML = 
              "<a href='#' id='link' "
              +"data-action='sayMyVariable'>Click Me</a>";
            this.container.html(localHTML);
        }
        Outside.prototype.clickHandler = function (e) {
            var action = e.target.getAttribute('data-action');
            if(action && typeof this[action] === 'function'){
                this[action](e);
            }else{
                throw new Error('Action:'+action
                  +' is not supported by Outside');
            }
        }
        Outside.prototype.sayMyVariable = function(e){
            console.log('The event:',e);
            console.log('this:',this);
            alert(this.myVariable);
        }
        //no need for document.ready for scripts executing right before </body>
        //even if this is not inline script but <script src=... it will still work
        //without document.ready
        var out = new Outside('output');
        out.generateHTML();
    </script>
</body>
</html>

More info on constructor functions and prototype can be found here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.