Backbone.js singular Models not in collection

2019-04-04 23:00发布

Being new to Backbone.js, just wanted to clarify the correct way to go about this simple task.

Developing a web app, almost always, you'll have user accounts, where users can login to your app, and view their personalized data. Generally, their page might show some widgets, their user information (name, avatar, etc).

Now creating a Model per widget and grouping these in a Collection is an easy concept. However, would their user info be stored in a singular Model, which would not be apart of a Collection?

If so, how is the hooked up with the rest of the app? Forgive my ignorance, but I've yet to come across any examples that don't explain Models not using them in Collections (User and Users, Dog, Cat and Animals, etc)

Anyway, sorry for the lengthly explanation. I would be looking for any resources to get me started on making a real-world app, rather than a ToDo app (which is great for the basic concept understanding)

2条回答
来,给爷笑一个
2楼-- · 2019-04-04 23:41

There is not any reason to feel forced to declare a Collection for every Model your App has. It is very common to have Models without Collection associated.

// code simplified and not tested
App.CurrentUser = Backbone.Model.extend({
  url: "http://myapp.com/session.json"
});

App.CurrentUserView = Backbone.View.extend({
  el: "#user-info",

  render: function(){
    this.$el.html( "<h1>" + this.model.get( "name" ) + "</h1>" );
  }
});

var currentUser = new App.CurrentUser();
currentUser.fetch();

var currentUserView = new App.CurrentUserView()({ model: currentUser });
currentUserView.render();
查看更多
We Are One
3楼-- · 2019-04-04 23:41

If you want a model / view with no collection, don't write a collection or collection view.

Add the view the same way you normally see the collection based view added.

查看更多
登录 后发表回答