Organizing subviews with backbone.js?

I apologize for being new to the spine, but I think I understand the concepts.

For example: you have models for a bookstore> Bookshelf> Book> Page

How would you organize this so that the views can be managed as follows:

Bookstore.render() //to view the bookstore Bookstore.bookshelf.get(shelfId).render() //to view shelf Bookstore.bookshelf.get(shelfId).book.get(bookId).render() //to view book Bookstore.bookshelf.get(shelfId).books.get(bookId).pages.at(0).render() //to view page 

Is this being done right?

+4
source share
2 answers

Yes, itโ€™s possible , and I created a working example for you, I think itโ€™s just another way to organize your BackBone JS architecture, and I think thatโ€™s a good idea.

explication

All models must have:

  • a render method that invokes the render method of its view. I am creating a base model that I use for the Bookshelf, Book, and Page models.

  • a initialize method, it creates a collection (books for bookshelves, pages for books ...)

Finally, I introduced the Bookstore model and did it!

code

Demo: http://jsfiddle.net/Atinux/DvbA3/show/

Try it in the console:

 Bookstore.render() Bookstore.bookshelves.get(1).render() Bookstore.bookshelves.get(1).books.get(2).render() Bookstore.bookshelves.get(1).books.get(2).pages.at(0).render() 

Code with comments is available here: http://jsfiddle.net/Atinux/DvbA3/

I think itโ€™s best to understand how the code works. Feel free to ask me if you have problems in order to understand my code perfectly.

JSON data

JSON data should look like this:

 var data = { bookshelves: [{ id: 1, name: 'Science', books: [{ id: 1, name: 'Abstract Algebra', pages: [ { content: 'Page 1 Abstract'}, { content: 'Page 2 Abstract'}, { content: 'Page 3 Abstract'} ] }, { id: 2, name: 'Chemistry and Technology of Fertilizers', pages: [ { content: 'Chemistry page 1' }, { content: 'Chemistry page 2' }, { content: 'Chemistry page 3' } ] } ] }, { id: 2, name: 'Psychology', books: [{ id: 1, name: 'How to Think Straight About Psychology', pages: [ { content: 'Psychology page 1' }, { content: 'Psychology page 2' }, ] } ] } ] }; 
+4
source

@Alley, what you want to do is against the MVC pattern, since your model objects must be agnostic to represent. @ Atinux's answer probably works, but introduces a direct relationship between your view and model objects.

All methods considered must be in view objects. The relationship between the view and the models must be done using events. So, instead of doing: Bookstore.bookshelf.get (shelfId) .render () you should do something like this: bookshelfView.render ()

0
source

Source: https://habr.com/ru/post/1388507/


All Articles