Backbone.js singular Models not in collection

断了今生、忘了曾经 提交于 2019-12-21 07:33:49

问题


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)


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/9822442/backbone-js-singular-models-not-in-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!