开发者

Mootools Classes and Binding

开发者 https://www.devze.com 2023-03-20 19:57 出处:网络
I am having trouble accessing both the Class and the current element. How can I have access to both the current element and the Class?

I am having trouble accessing both the Class and the current element. How can I have access to both the current element and the Class?

// Class stuff above
fuction1 : function () {
  myelements.addEvent('click', this.function2);
},
function2 : function () {
  // "this" is the开发者_开发技巧 element from function1
  this.getParent('div')

  // now I need to call another function
  // But since the scope is the element, I get an error
  // If I bind function two,
  // how can I gain access to the element?
  this.function3();
}
//Class stuff below

Thanks!


Here's a cleaner way. Note that the event is already passed to the method:

var Foo = new Class({

    initialize: function() {
        this.elements = $$('li').addEvent('click', this.click.bind(this));
    },

    click: function(e) {
        console.log(this); // Foo Class
        console.log(e.target); // the clicked this.elements item
    }

});

And a working example: http://jsfiddle.net/AtUgd/


I usually do something like this:

FooBar = new Class({
    initialize: function() {
        this.element = $('foobar');
        this.element.addEvent('click', function(e) { this.foo(e) }.bind(this));
    },
    foo: function(e) {
        console.log( $(e.target) );
    }
});


Note that e.target isn't always that element you really expect (the one you binded).

It's an element that is clicked so if your binded element contains something inside, click event will get bubbled up and it will fire, but you will have wrong element in e.target


If you want to pass event binded element to one of your class methods you can do it like this:

var self = this; // 'this' is class reference
elements.addEvent('click', function(e){
    self.myClassMethod(this, e); // now 'this' is clicked element
});

Now you got the right element passed to your method and ready to manipulate on.

0

精彩评论

暂无评论...
验证码 换一张
取 消