javascript - Backbone : Adding a model to Collection and render a View

标签 javascript backbone.js backbone-views backbone-routing

我正在构建一个简单的 Backbone 应用程序,其中主要有一个包含书籍列表的 View (书籍名称+封面图像)和另一个我想要将新书籍添加到列表中的 View 。

当我使用示例数据时,包含书籍的 View 可以正确呈现,但是当我尝试将书籍添加到列表中时,它不起作用,我不知道问题出在哪里。

这是 JSFiddle http://jsfiddle.net/swayziak/DRCXf/4/和我的代码:

HTML:

   <section class="menu">
      <ul class="footer"> 
        <li><a href="">List of Books</a></li>
        <li><a href="#edit">Edit</a></li>
        <li><a href="#about">About</a></li>
      </ul>
   </section>

   <section class="feed"></section> 

   <script id="bookTemplate" type="text/template">
       <img src="<%= image %>"/>
       <h2 class="bookTitle"><%= title %><h2>
   </script>

   <script id="aboutTemplate" type="text/template"> About </script>

   <script id="editTemplate" type="text/template">
       <form id="addBook" action="#">
           <label for="title">Book Title</label><input type="text" id="title">
           <label for="image">Image Link</label><input type="text"/ id="image">
           <button id="add-book">Button</button>                
       </form>
   </script>                

</div>

主干代码:

app = {};

//示例数据

var books = [
    {title:'Imperial Bedrooms', image:'http://upload.wikimedia.org/wikipedia/en/thumb/e/e8/Imperial_bedrooms_cover.JPG/200px-Imperial_bedrooms_cover.JPG
    },

    {title:'Less than zero', 
    image:'http://d.gr-assets.com/books/1282271923l/9915.jpg' 
    },

];

//路由器

app.Router = Backbone.Router.extend({
    routes: {
        '' : 'home',
        'about' : 'about',
        'edit' : 'edit',
    },

    home: function () {
        if(!this.bookListView){
            this.bookListView = new app.BookListView(books);
        }else{
        this.bookListView.render();
        }
    },

    about: function () { 
        if (!this.aboutView) {
            this.aboutView = new app.AboutView();
        }
        $('.feed').html(this.aboutView.render().el);
    },

    edit: function () {
        if (!this.editView) {
            this.editView = new app.EditView();
        );
            $('.feed').html(this.editView.render().el);
    }

});

//模型

app.Book = Backbone.Model.extend({
    defaults: {
        title:'',
        image:'',       
    }
});

//集合

app.BookList = Backbone.Collection.extend ({
    model: app.Book 
});

//图书 View

app.BookView = Backbone.View.extend ({
    tagName: 'div',
    className: 'book',

    template: _.template( $( '#bookTemplate' ).html()),

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
   }
});

//图书 ListView

app.BookListView = Backbone.View.extend({
    el: '.feed',

    initialize: function ( initialBooks ) {
        this.collection = new app.BookList (initialBooks);
        this.render();
        this.listenTo( this.collection, 'add', this.renderBook );
    },

    render: function() {
        this.$el.empty();

        this.collection.each(function( item ){
            this.renderBook( item );
        }, this);
    },

    renderBook: function ( item ) {
         var bookview = new app.BookView ({
              model: item
    });            

    this.$el.append( bookview.render().el );
    } 
});

//添加图书 View

app.EditView = Backbone.View.extend({
  tagName: 'div',
  className: 'edit',

  template: _.template( $( '#editTemplate' ).html()),

  events:{
     "click #add-book":"addBook"
  },

   addBook:function(e){
        e.preventDefault();

        var title = this.$el.find("#title").val();
        var image = this.$el.find("#image").val();
        var bookModel = new app.Book({title:"title",image:'image'});    
    },

  render: function () {
      this.$el.html(this.template());
      return this;
   }
});

//关于 View

app.AboutView = Backbone.View.extend({
    tagName: 'div',
    className: 'about',

    template: _.template( $( '#aboutTemplate' ).html()),

    render: function () {
        this.$el.html(this.template());
        return this;
     }
});

});

var router = new app.Router();
Backbone.history.start();

我认为问题与家庭路由器、app.BookListView 和 app.EditView 有关,但我不确定。

欢迎任何帮助。

谢谢。

最佳答案

在此示例中......为了简单起见,定义一个全局图书集合。

app.books = new app.BookList(books);

将您的图书集合传递给路由器中的 editView 和 BookListView:

home: function () {
  if(!this.bookListView) {
     this.bookListView = new app.BookListView({collection:app.books});
  } 
  else {
     this.bookListView.render();
   }
},
edit: function () {
  if (!this.editView)
    this.editView = new app.EditView({collection:app.books}); // your book collection
  $('.feed').html(this.editView.render().el);
}

在 editView 中,您需要对 addBook 函数进行一些更改:

app.EditView = Backbone.View.extend({
 // your other code above
   addBook:function(e){
    e.preventDefault();

    var title = this.$el.find("#title").val(); //could use: this.$('#title').val()
    var image = this.$el.find("#image").val();

    // remove quotes to pass variables
    var bookModel = new app.Book({title:title,image:image}); 

    // this.collection is app.books, your book collection.
    // this will trigger the add event in your BookListView.
    this.collection.add(bookModel);  
  },

});

BookListView 中对 initialize 函数进行以下更改:

app.BookListView = Backbone.View.extend({    

initialize: function() {
    this.render();
    this.listenTo( this.collection, 'add', this.renderBook );
},

这里是一个关于更改的 fiddle :http://jsfiddle.net/9R9zU/

关于javascript - Backbone : Adding a model to Collection and render a View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18001349/

相关文章:

javascript - 让主干路由正常工作

jquery - 主干网和jqm : back button how to restore page context

javascript - 从提交 React.js 生成元素

JavaScript 语法。这是什么: ", (err) => { }"?

javascript - 在 Canvas 上绘制动画曲线

javascript - 在 backbone.js 中如何触发 View 卸载事件?

javascript - Backbone : populate multiple drop-downs with the same data?

javascript - 返回在其数组中包含字符串的所有数组

javascript - Backbone.js - 是否可以为模型定义多个 el 值?

javascript - backbone.js subview 未在初始渲染中显示