JQuery UI Widget Programming
$.widget("ui.chatwindow", {
options: {
nickname: "obama";
},
setNickname: function(nick){
var self = this;
var id_pre = 'wchat_' + self.options.nickname;
$('#' + id_pre + '\\:name').text(self.options.nickname);
},
setStatus: function(status){
var self = this;
var id_pre = 'wchat_' + self.options.nickname;
switch(status){
case 1:
$('#' + id_pre + '\\:status').removeAttr('class');
$('#' + id_pre + '\\:status').addClass('chat-icon-online');
$('#' + id_pre + '\\:status').attr('title','Online');
break;
开发者_如何学Go ...
default:
break;
}
...
},
...
}
My Question is i always write in every method:
var self = this;
var id_pre = 'wchat_' + self.options.nickname;
to change element class or text content
is this a good or efficient way to code? let me know the good and efficient way to do this. thanks for your kind.I think this would be better on the code review site but I started something in the comments so I guess I should finish it.
First of all, if you're going to keep saying this:
var id_pre = 'wchat_' + self.options.nickname;
over and over again, you should do it just once in your _create
function:
_create: function() {
this.id_pre = 'wchat_' + this.options.nickname;
//...
}
Then you can just refer to this.id_pre
when you need it. You can do similar things with $('#' + id_pre + '\\:status')
:
_create: function() {
this.id_pre = 'wchat_' + this.options.nickname;
this.$id_pre = $('#' + id_pre + '\\:status');
//...
}
But keep in mind that caching jQuery objects like this can cause odd results if you're adding and remove elements that you've wrapped in $()
.
You only need to do this:
var self = this;
when you want to refer to the outer this
inside a callback. This simple variable is pretty cheap so I wouldn't worry about it but you should know why the idiom exists and when you need it.
精彩评论