模型不更新 Backbone.js

问题描述 投票:0回答:1

在我的backbone项目中,我在Collection中调用 "add "方法后,我的模型没有更新。我不明白为什么。

我确信我做了一些不好的事情,但我无法理解是什么原因。

https:/github.comlured75CardScoresblobmasterpublicjstweets.js。

在我的视图的初始化函数中,我调用绑定'添加'到this.render(视图的)。

initialize: function() {
            this.model.on('add', this.render, this);
},

在我的视图的渲染函数中,this.model没有具体的属性,只有{length: 1, models: Array(1), _byId: {...}, _events: {…}}

render: function() {
    console.log('in render this.model', this.model);
    ...
}

用于#new-tweet的提交事件的函数被很好地调用,tweet对象被很好地填充。

The method $('#new-tweet').submit(function(ev) {
            var tweet = new Tweet({ author: $('#author-name').val(), status: $('#status-update').val()});   
            console.log('adding : ', tweet.toJSON());
            tweets.add(tweet);

            return false;
        });

除了使用旧的框架之外,你是否发现了一些错误的地方?

javascript backbone.js
1个回答
1
投票

[描述]问题是,_.each的第一个参数必须是 "list"。(https:/underscorejs.org#each)

如你在TweetsView中的console.log(this.model),虽然是一个主干集合......

它是一个对象。

{
    length: 1, 
    models: Array(1), 
    _byId: {…}, 
    _events: {…}
}

所以各不能正常工作。

改进]我提供两种方法。

  1. 使用Backbone.Collection的every功能。
this.model.each(function(tweet, i) {
    console.log(i);
    console.log(tweet); // Undefined ???
    console.log((new TweetView({model: tweet})).render().$el);
    self.$el.append((new TweetView({model: tweet})).render().$el);
});
  1. 因为this.model.models是Array,直接访问它。
_.each(this.model.models, function(tweet, i) {
    console.log(i);
    console.log(tweet); // Undefined ???
    console.log((new TweetView({model: tweet})).render().$el);
    self.$el.append((new TweetView({model: tweet})).render().$el);
});
© www.soinside.com 2019 - 2024. All rights reserved.