Javascript this. context clobbered by event handlers

2 posts, 0 answers
  1. Michael
    Michael avatar
    6 posts
    Member since:
    Dec 2012

    Posted 29 Dec 2012 Link to this post

    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.



  2. Atanas Korchev
    Admin
    Atanas Korchev avatar
    8462 posts

    Posted 31 Dec 2012 Link to this post

    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!
  3. Kendo UI is VS 2017 Ready
Back to Top