主干中的模型属性未定义

The model attribute in backbone is not defined?

本文关键字:属性 未定义 模型      更新时间:2023-09-26

我使用主干网来构建我的客户端应用程序,我想做的是每次用户点击时显示一个笑话。get_joke on a event:heres my backbone app code:

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,但它说笑话还没有定义,但我不知道问题在哪里。谢谢

首先,你不能相信console.log对复杂对象的描述:

  • Backbone.js空数组属性
  • Backbone.js model.get()返回';未定义';即使我可以在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" });

尝试以下操作:

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

我也会注销以下内容:

newJoke.toJSON()

查看实际要渲染的内容。