【问题标题】:Backbone.js how to work with fetched ItemsBackbone.js 如何处理获取的项目
【发布时间】:2011-11-21 09:36:52
【问题描述】:

我正在尝试学习 Backbone.js,但我似乎在获取模型时遇到了问题。我有:

window.News = Backbone.Model.extend({
    urlRoot: "/rest/news"
});

window.NewsItems = Backbone.Collection.extend({
    model: News,
    url: "/rest/news"
});

window.NewsView = Backbone.View.extend({
    el: $(".newsItem"),

    events: {
        "click .edit": "editNews" 
    },

    editTemplate: $('#tmpl-edit-news-item').template(),

    editNews: function(evt) {
        console.log("EDIT CLICKED");
        var ele = $(evt.target);
        var news = new News({id:1});
        news.fetch();
        console.log(news);
        console.log(news.get('title');
     }

});

new NewsView();  

我在页面上有一个元素具有 class="edit" data-id="$ID"。当我单击该元素时,一切都按预期进行。 Backbone 运行 editNews 函数,“EDIT CLICKED”显示在控制台中,console.log(news) 输出一个对象。在该对象内部,我注意到有一个属性字段,其中包含服务器加载的新闻项的 json。所以服务器正在工作并发送回json。有一个标题字段设置为“测试新闻标题”,但运行 console.log(news.get('title')) 返回未定义。

我是否需要将获取的数据传递给某个东西以将其转换为骨干模型?我认为使用 fetch 将返回的 json 数据放入模型中。

附加信息:

url requested: http://localhost/rest/news/1  
response data: {"class":"org.backbonetest.News","id":1,"content":"This is test content","dateCreated":"2011-09-20T16:19:56Z","lastUpdated":"2011-09-20T16:19:56Z","shortDescription":"","title":"Test News Title"}

【问题讨论】:

    标签: javascript rest backbone.js


    【解决方案1】:

    好的,因为获取是异步的,所以我不能立即调用 console.log。添加成功函数允许对象作为模型工作。

    var news = new News({id:1});
    news.fetch();
    console.log(news);
    console.log(news.get('title');  
    

    变成

    news.fetch({success: function() {
                            console.log(news.get("title"));
                         },
                         processData: true
               });  
    

    这会返回正确的标题。

    【讨论】:

    • 提取选项中的processData 是什么?
    • 我不认为我会这样做。看看@ant_Ti 的建议。 “主干”方式是绑定到模型/集合上的“更改”或“重置”事件。从视图中,您通常会绑定到“渲染”,并且渲染函数会更新视图的该部分。 “成功”回调通常用于其他事情。
    【解决方案2】:

    应该是这样的:

    editNews: function(evt) {
        console.log("EDIT CLICKED");
        var ele = $(evt.target);
        var news = new News({id:1});
    
        // fetch is asynchronous process so we will bind handler to model's change event
        news.bind('change', function(model, value) {
            console.log(news);
            console.log(news.get('title');
        }, this)
        news.fetch();
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2014-10-01
      • 1970-01-01
      • 2020-04-19
      • 2011-09-26
      • 1970-01-01
      相关资源
      最近更新 更多