最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - backbone.js set model attribute inner field - Stack Overflow

programmeradmin3浏览0评论

I want to set an attribute of a backbone.js model, but only an inner field rather than the entire field.

Example code might be:

model.set('user.avatar', 'img')

Anything I can do?

Thanks

I want to set an attribute of a backbone.js model, but only an inner field rather than the entire field.

Example code might be:

model.set('user.avatar', 'img')

Anything I can do?

Thanks

Share Improve this question asked Dec 26, 2011 at 11:00 HarryHarry 54.9k76 gold badges185 silver badges270 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

You could simply make a copy of the object, set the attribute, and then re-set it on the original model:

var userAttributes = model.get("user");
userAttributes.avatar = "img";
model.set("user", userAttributes)

Or add a function to set parts of the user on the model from an object:

model = Backbone.Model.extend({
...
setUser: function(attributes){
    var user = this.get("user") || {};
    _.extend(user, attributes);
    this.set({user:user});
},
...

Then pass in attributes like so: model.setUser({avatar: "img"});

发布评论

评论列表(0)

  1. 暂无评论