0

我使用主干来构建我的客户端应用程序,我试图做的是每次用户在事件上单击 .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 时出现问题,它不会将笑话呈现到视图中,我知道模型已被获取,因为我检查了 console.log,但它说笑话尚未定义,但我不知道在哪里问题是。谢谢

4

2 回答 2

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" });
于 2012-09-06T12:09:30.597 回答
0

尝试以下操作:

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

我还会注销以下内容:

newJoke.toJSON()

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

于 2012-09-06T11:53:05.263 回答