Mootools: toElement 方法

MooTools 1.2另一个新特点是toElement方法(但并没有在其官方文档里说明),可以添加到您的类(或对象)中。这个方法的灵感来自 Prototype framework,MooTools 开发者认为在精简 classes中是非常有用的,并在M ooTools中采用了它,并把它放入了核心。

Note: its not yet documented but its already in the 1.2.0 version.

toElement 只是一个返回 element 对象的方法。当向 $ 传递一个对象时,它会尝试调用对象的 toElement 方法来取得当前 element。

参考资料来自http://blog.kassens.net/toelement-method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var User = new Class({
	initialize: function(name){
		this.name = name;
    },
	toElement: function(){
		if (!this.element) {
			this.element = new Element('div', {'class': 'user'});
			var avatar = new Element('img', {
				src: '/avatars/' + this.name + '.jpg'
			});
			var description = new Element('div', {
				'class': 'username',
				'text': this.name
			});
			this.element.adopt(avatar, description);
		}
		return this.element;
		}
 
	});
    window.addEvent('domready',function(){  
        var alice = new User('Alice');
        var bob = new User('Bob');
        $(alice).inject('header', 'after');
        // let's inject bob after alice
        $(bob).inject(alice, 'after');					
});

我认为这些代码已经不言自明了。不过还有一件事是值得一提的:
toElement doesn’t create a new element each time it’s called, but stores the element in this.element and only creates it if it’s not already created.
我们通过添加一个方法,来说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var User = new Class({						
    setName: function(name){
		// store it to the class
		this.name = name;
		// we're done when the element is not yet created.
		if (!this.element) return;
		// update the element:
		this.element.getElement('div').set('text', name);
		this.element.getElement('img').set('src', '/avatars/' + name + '.jpg');
    },
	initialize: function(name){
		this.name = name;
    },
	toElement: function(){
	    if (!this.element) {
			this.element = new Element('div', {'class': 'user'});
			var avatar = new Element('img', {
				src: '/avatars/' + this.name + '.jpg'
			});
			var description = new Element('div', {
				'class': 'username',
				'text': this.name
			});		
			this.element.adopt(avatar, description);
		}
		return this.element;
	}  
});
window.addEvent('domready',function(){
	var alice = new User('Alice');
	var bob = new User('Bob');
	bob.setName('bobby');
	$(alice).inject('header', 'after');
	// let's inject bob after alice
	$(bob).inject(alice, 'after');				
});

Class.toElement

Class.toElement. Class.toElement allows you to pass the $ (or document.id) method an instance of your class and the instance will be treated as an element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
window.addEvent('domready',function(){
var myClass = new Class({
	initialize: function(container,options) {
		this.container = $(container);
	},
 
	toElement: function() {
		return this.container;
	}
});
 
var mc = new myClass('wrapper');
$(mc).fade('out'); 
});

参考资料来自http://davidwalsh.name/mootools-tip-class-toelement

 

站点统计