骨干网中的模型属性没有定义?

时间:2012-09-06 11:47:31

标签: javascript backbone.js

我使用骨干来构建我的客户端应用程序,我试图做的是每次用户点击事件上的.get_joke时显示一个笑话:继承我的骨干应用程序代码:

JokeModel = Backbone.Model.extend({
   url: '/jokes'
   initialize: function() {
      this.fetch();
  }
});

JokeView = Backbone.View.extend({
    template: _.template("<p><%= joke %></p>")
    events: {
      "click .get_joke" : "render"
  } 
    render: function() {
       var newJoke = new JokeModel;
       $(this.el).html(this.template(newJoke.toJSON()));
  }
});

newJokeView = new JokeView;

问题,当我点击.get_joke它deosnt渲染笑话到视图,我知道模型已被提取,因为我检查与console.log,但它说笑话尚未定义,但我不知道问题所在。感谢

2 个答案:

答案 0 :(得分:3)

首先,你不能相信console.log关于复杂对象的内容:

正在发生的事情是joke.fetch()是异步的,当您致电jokeView.render()时,模型仍未准备好。

你应该修改一下你的架构,并为每个笑话指定一个合适的视图,这样你就可以为每个笑话提供一个需要时显示它的视图。

// code simplified an not tested
JokeModel = Backbone.Model.extend({
   url: '/jokes'
});

// This View is new and it is taking care only for the common event "click .get_joke"
// which is not related with any Joke in particular
// This View should be in charge of the JokesCollection 
// but I don't want to make things more complicate
JokeControls = Backbone.View.extend({
  events: {
    "click .get_joke" : "render"
  }, 

  getJoke: function(){
    var joke = new JokeModel();
    var view = new JokeView({ model: joke, el: this.$el.find( ".joke-wrapper" ) });
    joke.fetch();
  },
});


// This is the View that is related with unique Joke
JokeView = Backbone.View.extend({
    template: _.template("<p><%= joke %></p>"),

    initialize: function(){
      // see how it shows itself when the Model is ready
      this.model.on( "change", this.render, this );
    },

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

// Activate the Joke Controls
newJokeControls = new JokeControls({ el: "#joke-controls" });

答案 1 :(得分:0)

尝试以下方法:

JokeModel = Backbone.Model.extend({
   url: '/jokes'
   parse : function(data) {
      console.log(data);
      return data;
   }
   initialize: function() {
      this.fetch();
  }
});

我还会注销以下内容:

newJoke.toJSON()

要查看您实际尝试渲染的内容。