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

时间:2012-08-22 13:21:20

标签: javascript backbone.js requirejs

我想将TodoListView中的模型todo项目传递给TodoView。但它不能。我的代码是这样的。

    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;
});

我不明白为什么TodoView中的this.model.get(“title”)方法输出undefined。你有什么主意吗?谢谢你。

2 个答案:

答案 0 :(得分:1)

如果检查模型的属性,你会得到什么?

console.log(this.model.attributes)

是否有“title”属性?

此外,您可能希望绑定render()的上下文。在初始化中:

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

答案 1 :(得分:0)

我的收藏已将项目设置为未定义为0 idx。所以,它会导致错误。

我用这段代码解决了......

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

谢谢大家。