简体   繁体   中英

backbone.js can't pass model item from collection's view to item's view

I want to pass model's todo item from TodoListView from to TodoView. But it can't. My code is like this.

    define(["jquery","underscore","backbone","todo_view","todo"],
function($,_,Backbone,TodoView,Todo){
    var TodoListview =  Backbone.View.extend({
    tagName: "ul",
    initialize:function(){
    _.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
    _.bindAll(this,"addTodo","render");
    this.collection.bind("add",this.addTodo,this);
                       this.collection.bind("reset",this.render,this);

                    },
    render:function(){
      this.$el.empty();
      this.collection.each(this.addTodo);
      return this;
      },
    addTodo:function(item){
      console.log(item.get("title"));
      // it's works correctly -> Backbone.model
      var todoView = new TodoView({model:item});
      var str = todoView.render().$el;
      this.$el.append(str);
      }
    });
    return TodoListview;
    });


// todo_view.js
define(["backbone","underscore"],function(Backbone,_){
    var TodoView = Backbone.View.extend({
            tagName: "li",
            template: "#todo-view-template",
            events: {
                "click .done": "toggleDone"
            },
            initialize:function(){
                _.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
                this.render();
            },
            render:function(){
                var str = $(this.template).html();
                var template = _.template(str,{name: "hello"});
                            console.log(this.model) //#-> Backbone.Model.
                            console.log(this.model.get("title")
                             //#-> undefined get method. why??
                return this;
            },
            toggleDone:function(){
            }
    });


    return TodoView;
});

I don't understand why this.model.get("title") method in TodoView outputs undefined. Do you have any idea? Thanks advance.

What do you get if you inspect the model's attributes?

console.log(this.model.attributes)

Does it have the "title" attribute?

Additionally you might want to bind the context for render(). In initialize:

initialize:function(){
   _.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
     _.bindAll(this, 'render');
            this.render();
   },

My collection has set item to undefined at 0 idx. So, it cause error.

I solved by this code...

if (typeof this.model !== undefined){
 this.model.get("title");
 }

Thanks for all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM