1

I had create two objects: User and Blog and I need to associate both of them. My thought was to create an ID for each and then make the association. The ID is created through array.length at the moment of creating an instance.

The associateUserWithBlog functions stores the blog with respective user. At user instance I define an array for store all blogs create by user. My question is if there is another way to do this association. I'll need later print all the blogs and its owner(user) and sometimes I struggling to print.

function User(name, level, title, id, entry, comment) {
     this.name = name;
     this.level = level;
     this.title = title;
     this.id = id;
     this.entry = entry;
     this.comment = comment;
}

function Blog(blogID, title, userID, blogText) {
     this.blogID = blogID;
     this.title = title;
     this.userID = userID;
     this.blogText = blogText;
     this.comment = comment;
}

users = new Array();
blogs = new Array();

function associateUserWithBlog(userID, entryID) {
    users[userID].entry = entryID;
}

// user with id = 0
userID = users.length
var user = new User(userID, "Bob", "Student", "Mr", new Array())

// blog with id = 0 and user associate with id = 0
blogID = blogs.length
var blog = new Blog(entries.length, "Blog 1", 0, "Welcome Blog 1");

associateUserWithEntry(userID, blogID);
2
  • 1
    You could associate them quite directly by setting one as the property of another: Blog.user = new User('name', 'level', ...). Commented Oct 23, 2015 at 1:24
  • You should rather keep blogs inside the user as an association. As User to Blog relationship is one to many, I suggest you create an array of blogs inside a user object. That way deletion of a blog will not delete the user. Deletion of a user will delete all his blogs. Commented Oct 23, 2015 at 1:35

1 Answer 1

2

The following creates a user with any number of blogs owned by him as an association.

You can add more specific behaviors to the user object and convert it into a module pattern. I have added a snippet which gives a brief outline of such an object.

function createUser(userOpts) {
    //private members
     var name = userOpts.name;
     var level = userOpts.level;
     var title = userOpts.title;
     var id = userOpts.id;
     var entry = userOpts.entry;
     var comment = userOpts.comment;
     var blogs = userOpts.blogs || [];
  return {  
      
      //All methods to manipulate private data
    
     createBlog:function() {...} 
     getBlogs: function() { return blogs.slice(); }
     //...other methods
  };  
 }
  
 
  var user = createUser(opts);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.