문제

Talking about XBL is not exactly talking about javascript. So I'll create this question that's related to this one, but now about XBL, where I'm not the creator of the root javascript code, but just of the methods and event handlers inside the bindings.

--

In some cases, the this keyword may not refer to the object I expect it to. (recent example: in an key event, in my XBL)

What's the best approach to avoid this kind of mistake?

For now, I'm using always the getElementById (or $.fn from jQuery), but I'm not sure if it's the best approach.

--update

A little bit more details:

Within a XBL method the only way to access the element that was defined in the Xul file (the GUI description file) without using "this" (as it may not be the "this" I expect) is with getElementById, and this makes the code not reusable, so I'm looking for alternatives..

도움이 되었습니까?

해결책

As you've heard elsewhere, the problem is that the this parameter isn't necessarily the object you first thought of, especially when you're talking about event handlers and the like. The best way I found is to write a small function that will bind some object as the this variable and return another function that uses the binding to call the original function.

Take a look at this code:

var bindFunction = function(self, f) {
  return function() {
    return f.apply(self);
  };
};

var foo = function() {
  alert(this.hello);
};

var bar = { 
  hello: "Hello there"
};

var boundFoo = bindFunction(bar, foo);
boundFoo();

What I have is a function called bindFunction that takes an object (called self) and some function, and returns another function that will call the passed-in function applying the self object as the this variable.

The rest of the code is just some test code: a foo function that will alert this.hello, a bar object with a hello member, and how you can bind foo with bar.

In essence, I've taken a function that accepts no parameters and generated another function that will ensure the first is always called with the correct this variable. Ideal for event handlers.

(Sorry, but I know nothing about XBL, so I hope this will be of use.)

다른 팁

If there's not a best answer, a good approach could be use javascript files instead of XBL for the implementation. Looking the Xulrunner source code, looks like most code does this.

But I still would like to use XBL, if there was a way to work fine with it..

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top