0

I am trying to work with ubonstrustive dom ready that looks something like this,

  var app = {

    common : {

        init: function() {

            //Initialisate the request object
            app.request.init();
        }

    },

    request: {

        users : "helloworld",

        init: function() {
            alert("...request started...");
            $('form').on('change', '#workbase', this.workBaseChange);
        },

        workBaseChange: function(e) {
            var that = this;
            console.log(this);
        }

    },

    validation : {}

}

UTIL = {

    fire : function(func, funcname, args) {

        var namespace = app;
        funcname = (funcname === undefined) ? 'init' : funcname;
        if(func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function') {
            namespace[func][funcname](args);
        }

    },

    loadEvents: function() {
        UTIL.fire('common');
        $.each(document.body.className.split(/\s+/), function(i, classnm){
            UTIL.fire(classnm);
        });
    }
};

$(document).ready(UTIL.loadEvents);

request.workBaseChange fires when a select menu is changed, but if log this in that function it return the changed select not the request object as I would expect, am I doing something incorrectly? How do I get the context of request{}?

Udders
  • 6,340
  • 22
  • 91
  • 164
  • See this: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Dec 02 '16 at 11:29

1 Answers1

0

Try

$('form').on('change', '#workbase', this.workBaseChange.bind(this)); 

You can find more info here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Note if using IE this is only supported in IE9 or later. There is a polyfill on the link above however.

this.workBaseChange is the callback supplied to the jquery event. In the callback, the 'this' value is set to the element that triggered the event which is the select. The bind function returns a new function with the value of 'this' scoped to that function which then sets the 'this' property to the value that you supplied.

Also see here in the jquery docs (Context, Call and Apply):

http://api.jquery.com/Types/#Function

In JavaScript, the variable "this" always refers to the current context. By default, "this" refers to the window object. Within a function this context can change, depending on how the function is called.

All event handlers in jQuery are called with the handling element as the context.

See this working here: https://jsfiddle.net/mzxrhz8t/

mbx-mbx
  • 1,705
  • 11
  • 23