Reputation: 415
I have a simple jQuery ready
event that initializes a view by calling the a function in the setupView
object.
The question I have is, what is appropriate way to call the function setSomethingImportant
from the init
function as shown below?
Since the call is made from a different execution context than the init
function, this.setSomethingImportant()
does not work. However it works if I use setupView.setSomethingImportant()
. The problem I have with this is that if the var name (setupView
) changes, I will have to change the body of the code as well.
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant();
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);
Upvotes: 3
Views: 1926
Reputation: 18155
Please note that I changed my original solution. I am now passing data to the event handler using even.data.
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change({ _this: this }, function (event) {
console.log("Changed =" + $(this).val());
event.data._this.setSomethingImportant();
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);
Upvotes: 1
Reputation: 12420
Store this
into a variable:
var setupView = {
currentState: "CT",
init: function() {
// Keep a reference to 'this'
var self = this;
$("#externalProtocol").change(function() {
console.log("Changed =" + $(this).val());
// Use the old 'this'
self.setSomethingImportant();
});
},
setSomethingImportant: function() {
this.currentState = "TC";
console.log("Something has changed :" + this.currentState);
}
};
See the Working demo.
Upvotes: 4
Reputation: 2288
Just declare the function separately and then call like so:
function setSomethingImportant(context) {
context.currentState="TC";
console.log("Something has changed :" + context.currentState );
};
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant(this);
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
setSomethingImportant(this);
}
}
}(jQuery);
Upvotes: 1