Hi, i’m creating chat ui with JQueryUI.
here some code:
$.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;
...
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:
over and over again, you should do it just once in your
_createfunction:Then you can just refer to
this.id_prewhen you need it. You can do similar things with$('#' + 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:
when you want to refer to the outer
thisinside 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.