0

Ninjas.

I would like to know two things.

  1. How to call the functions 'Initialize()' and 'FillValidateView()'. I wrote where I want to call these functions inside the following code.

  2. I'm new to JavaScript programing. I would like to know if the following code is right to implement page transitions.

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>
    <div id="header">
        <p></p>
    </div>

    <div id="main">
        <div id="validate_or_import">
            <input type="button" id="go_validate" value="Validate Data">
            <inp ut type="button" id="go_import" value="Import Data">
        </div>
    </div>

</body>
</html>

JavaScript

$(function () {

    var View = function () {
        this.title = ''
    };

    View.prototype = {
        Initialize: function () {
            this.title = '';
            this.tiles = [];
            $('#main').children().hide();
        },
        Render: function () {
            $('#header p').html(this.title);
            jQuery.each(this.tiles, function () {
                this.show();
            });
        },
        FillFirstView: function () {
            this.title = 'Select what you want';
            this.tiles.push($('#validate_or_import'));
            $('#go_validate').on('click', function () {
                // I want to call 'Initialize()' and 'FillValidateView()' here!!!!!
            });
            $('#go_import').on('click', function () {
                alert('Not implemented yet');
            });
        },
        FillValidateView: function () {
            this.title = 'Validate data';
            //I will write more about this view
        }
    };

    var view = new View();
    view.Initialize();
    view.FillFirstView();
    view.Render();

});
Vijay
  • 7,211
  • 9
  • 38
  • 69
Nigiri
  • 2,759
  • 4
  • 22
  • 47

2 Answers2

3

(1) It's a bit tricky because the value of this won't be the original object in the callback. You could do:

var that = this;
$('#go_validate').on('click', function () {  
  that.Initialize();  
});

Or:

$('#go_validate').on('click', (function() {
  this.Initialize();
}).bind(this));

More infos in the this keyword: How does the "this" keyword work?

Community
  • 1
  • 1
Aegis
  • 1,679
  • 11
  • 12
1

Other answers showed how to capture this manually, but jQuery provides a dedicated facility for that: $.proxy. This is how to use it with your example (reduced for clarity):

$(function () {

    var View = function () {
    };

    View.prototype = {
        Initialize: function () {
            console.log('hi')
        },
        FillFirstView: function () {
            $('body').on('click', $.proxy(function () {
                this.Initialize()
            }, this));
        }
    };

    var view = new View();
    view.FillFirstView();

});
georg
  • 195,833
  • 46
  • 263
  • 351