This is a migrated thread and some comments may be shown as answers.

Javascript this. context clobbered by event handlers

1 Answer 62 Views
Button (Mobile)
This is a migrated thread and some comments may be shown as answers.
Michael
Top achievements
Rank 1
Michael asked on 30 Dec 2012, 02:51 AM
If we use the proper KendoUI syntax for calling an event, on an object instance...
<a data-role="button" data-click="myClass.addToList" data-mynumber>Add me</a>
This in the called method is clobbered....
function MyClass() {
};
 
MyClass.prototype.list = [1, 2, 3];
MyClass.prototype.addToList = function(e) {
 
   // 'this' is clobbered
   this.list.push(e.sender.context.dataSet.mynumber);
 
   // list thrown as undefined.
}
 
var myClass = new MyClass();
If we use the kendo.Class.extend method of making a Class, it's the same deal...

Any way out of this scope clobbering?  It's also a bit mystifying that it's a "feature" since we get the DOM payload through "e"

I'd like to call this a bug report, when an object method is called with an event handler, the object container should be set as this/context.



1 Answer, 1 is accepted

Sort by
0
Atanas Korchev
Telerik team
answered on 31 Dec 2012, 09:54 AM
Hello,

 This is currently by design and is documented here. The `this` of the event handler is set to the object which raises the event.

 The resolution of the scope ("this") in JavaScript is determined at runtime. Thus it is not possible to know what "this" is when you only have the function itself. Here is an example showing that: http://jsbin.com/opuram/1/edit. Calling the "foo" method by its alias makes `this` to be the global object - the `window`.  To properly specify the context one should either create a closure or use apply or call

 Perhaps Kendo UI can be enhanced to parse the event handler name and automatically create closures so `this` is the owner of the function and not the widget. This would be a breaking change though.

The other option is to have a new attribute which would specify what the context is:

<a data-role="button" data-click="addToList" data-handler="myClass">Add me</a>

If you like any of those ideas feel free to suggest them in our feedback portal. If it gets user interest we would implement it in a future release.


Regards,
Atanas Korchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Tags
Button (Mobile)
Asked by
Michael
Top achievements
Rank 1
Answers by
Atanas Korchev
Telerik team
Share this question
or