开发者

Upgrading a Model (backbone.js)

开发者 https://www.devze.com 2023-04-05 07:07 出处:网络
Right now I have a generic User model for all users. When a user logs it\'s determined wether they are user type 1 or user type 2. These two types need totally different models to represent them but s

Right now I have a generic User model for all users. When a user logs it's determined wether they are user type 1 or user type 2. These two types need totally different models to represent them but still include everything found in the generic User model.

My goal is开发者_StackOverflow up upgrade the User model for each type of user by passing the state from the current User model into the Type1 or Type2 model.

(in coffeescript)

class Type1 extends User
    #add super set of methods


#user arrives

user = new User

#after logging in

state = user.toJSON()

#do I need to unbind/delete the current user model?

user = new Type1(state)

Is this the best way to achieve this?

Thanks!


You could do that. You could also just copy over the attributes:

userCopy = new Type1
userCopy.attributes = user.attributes
delete user

Note that with either approach, you'll lose event bindings, etc. A safer, more JavaScript-y approach would be to just extend user in-place with additional methods, rather than having a Type1 class at all. (Of course, there are downsides to that to, such as losing the ability to invoke super from those methods. See my answer to a similar question here.)

0

精彩评论

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