My problem is the context of 'this' inside jquery callback.
$('input').on('change', function(){
this.number = $(this).val();
});
Above, this is the input element, which is normally what we want 'this' to be. The problem is that when it becomes a method of an object as below.
// constructor pattern
var View = function(){
this.number = 0;
};
// method definition
View.prototype.foo = function(){
$('input').on('change', function(){
// former this should be the object instance and
// the latter should be the html element.
this.number = $(this).val();
});
};
To change the context of this of the function, Function.bind() can be used as below.
View.prototype.foo = function(){
$('input').on('change', function(){
this.number = $(this).val();
}.bind(this)); // bind the callback to the instance of View object
};
Above works until $(this).val() since then $(this) wants the input element back not the View object.
In order to solve this in ad-hoc manner, I can explicitly set this to be the name of an instance as below.
View.prototype.foo = function(){
$('input').on('change', function(){
// explicitly set this to be the instance
// while sacrificing generality since code breaks when the object name is not 'view'
view.number = $(this).val();
});
};
var view = new View();
As you can see, this can resolve ambiguity of this but also compromises generality since code breaks when the object name is not 'view'.
Given above, how can I make the code resolve ambiguity while not compromising generality? Please suggest a way. Thank you.