我有简单的用户模型:
var user = Backbone.Model.extend({
initialize: function(){
this.bind("change:auth", function (){
if(this.get("auth") == true){
$.cookie('auth', true);
$.cookie('username', this.get("username"));
$.cookie('sessid', this.get("sessid"));
console.log(this)
console.log(this.attributes)
}else{
$.cookie('auth', null);
$.cookie('username', null);
$.cookie('sessid', null);
}
});
},
defaults : {
'auth' : $.cookie('auth'),
'username' : $.cookie('username'),
'sessid' : $.cookie('PHPSESSID')
},
logout : function (){
this.clear();
}
});
我不知道为什么会这样,但是当使用set
方法(以及触发更改事件)时,第一个控制台日志是:
_callbacks
Object { change:auth=[1]}
_changed
false
_changing
false
_escapedAttributes
Object {}
_previousAttributes
Object { auth=true, username="admin", sessid="roo74p7m7t0a3erke8r3vsat33"}
_unsetAttributes
null
attributes
Object { auth=true, username="admin", sessid="roo74p7m7t0a3erke8r3vsat33"} //<-- under this.attributes.username is string
cid
"c0"
defaults
Object { sessid="roo74p7m7t0a3erke8r3vsat33", auth=null, username=null}
idAttribute
"id"
constructor
function()
_performValidation
function()
bind
function()
change
function()
changedAttributes
function()
clear
function()
clone
function()
destroy
function()
escape
function()
fetch
function()
get
function()
has
function()
hasChanged
function()
initialize
function()
isNew
function()
logout
function()
parse
function()
previous
function()
previousAttributes
function()
save
function()
set
function()
toJSON
function()
trigger
function()
unbind
function()
unset
function()
url
function()
__proto__
Object { defaults={...}, _changed=false, idAttribute="id"}
Everythings似乎没问题,但第二个console.log(this.attributes)是:
Object { auth=true, sessid="roo74p7m7t0a3erke8r3vsat33", username=null} // oh no now it's null
总之,this.attributes.username的值已更改为对其执行任何操作。知道如何解决它吗?
答案 0 :(得分:3)
这只是与Firebug有关的一个小怪癖。我假设您一次设置一些属性,如下所示:
var myuser = new user();
myuser.set({sessid:"roo74p7m7t0a3erke8r3vsat33", auth:true, username:"admin"});
发生了什么事,{<1}}事件在模型中设置用户名之前被称为。因此,第二个change:auth
是正确的,尚未设置用户名,因此它不会显示在那里。
您在第一个console.log
中正确查看所有内容的原因是因为您正在记录对console.log
对象的引用,而不是副本。当您单击控制台中的对象时,所有属性都已设置,因此您可以在那里看到它们。
因此,您的代码运行正常,所有属性都已设置。您应该可以在设置属性后立即添加user
来验证这一点,如下所示:
console.log
另一种证明此案例的方法,如果您将var myuser = new user();
myuser.set({sessid:"roo74p7m7t0a3erke8r3vsat33", auth:true, username:"admin"});
console.log(myuser.attributes);
移至username:"admin"
对象之前auth:true
,请执行以下操作:
set
您应该会看到用户名显示在第二个var myuser = new user();
myuser.set({sessid:"roo74p7m7t0a3erke8r3vsat33", username:"admin", auth:true});
中,因为在调用console.log
之前已经设置了用户名属性。