0

我想将模型的待办事项从 TodoListView 传递给 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") 方法输出未定义。你有什么主意吗?提前谢谢。

4

2 回答 2

1

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

console.log(this.model.attributes)

它有“title”属性吗?

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

initialize:function(){
   _.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
     _.bindAll(this, 'render');
            this.render();
   },
于 2012-08-22T13:35:39.727 回答
0

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

我通过这段代码解决了......

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

谢谢大家。

于 2012-08-22T13:54:32.667 回答