开发者

MooTools Chaining

开发者 https://www.devze.com 2022-12-19 10:46 出处:网络
I don\'t think a function/method shoul开发者_StackOverflowd ever return void—instead, it should return this. That\'s why I was surprised to find out that this doesn\'t work:

I don't think a function/method shoul开发者_StackOverflowd ever return void—instead, it should return this. That's why I was surprised to find out that this doesn't work:

$('buttonContainer').getElement('input').set('value', this.get('value') + '  ');

What the code is suppose to do is find an <input> that is a child of the element with id attribute value of buttonContainer, and add two space characters to its value attribute. The aforeshown code errors though, and I'm forced to write:

var input = $('buttonContainer').getElement('input');
input.set('value', input.get('value') + '  ');

Doesn't MooTools have a way to chain these two seperate statements into one? Something similar to my first snippet?


MooTools cannot rebind this on the fly for every method called. This would be impossible.

You have to understand that every single call to your chain is in the same scope, therefore this remains the same. jQuery and every single other framework have the same problem. If you want to do two operations on an element at the same time, you must store the object in a variable and then use that variable to reference the object exactly like you did in your second example:

var input = $('buttonContainer').getElement('input');
input.set('value', input.get('value') + '  ');

this can only change when the scope changes (which in JavaScript is always when you hit a brace {} enclosing a function). This is not a limitation of MooTools' chaining. It's the way JavaScript in general works.


What you are asking has nothing to do with chaining. this has no context, so your call fails. The solution you are not happy with is the way you will need to write it for other values/attributes, but for a straight forward change like this, write it this way:

$('buttonContainer').getElement('input').value += '  ';
0

精彩评论

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