简体   繁体   English

骨架.js无法将模型项从集合的视图传递到项的视图

[英]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. 我想将模型的待办事项从TodoListView传递到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. 我不明白为什么TodoView中的this.model.get(“ title”)方法输出未定义。 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(). 另外,您可能想为render()绑定上下文。 In initialize: 在初始化中:

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

My collection has set item to undefined at 0 idx. 我的收藏集将item设置为undefined,值为0 idx。 So, it cause error. 因此,它会导致错误。

I solved by this code... 我通过这段代码解决了...

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

Thanks for all. 谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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