【问题标题】:Fetching from Model has not supply the defaults从模型中获取没有提供默认值
【发布时间】:2014-09-17 05:30:03
【问题描述】:

在我的应用程序中,我从 /home -by home Model 获取数据。模型包含默认对象。但是当我获取数据时,我看不到模型中的默认对象。

这是我的模型:

define(['backbone'], function(Backbone){
    "use strict";
    socialApp = window.socialApp || {};

    socialApp.homeModel = Backbone.Model.extend({
        url: "/home",
        defaults:{
            "category":"Level-1"
        }
    });

    return socialApp.homeModel;
});

这是我的 view.js :

socialApp.homeView = Backbone.Marionette.ItemView.extend({
            tagName:'div',
            initialize:function () {
                var that = this;
                this.model.fetch().done(function(data){
                    that.render(data) // i am fetching here
                });
            },

            render: function (data) {
                console.log(data) //there is no defaults object here...
                this.$el.html(homeTemp(data));
            }
        });

这里有什么问题?我使用Nodejs 作为服务器。

这是我得到的控制台:

{
__v: 0
_id: "5416ce23fc0c41ec0f03f672"
email: "afzil@gmail.com"
firstName: "Mohamed"
lastName: "Afzil"
password: "afzil"
username: "afzil"
}

感谢您。

【问题讨论】:

  • 控制台记录 this.model 并检查
  • this.modelsocialApp.homeViewsocialApp.homeModel 实例中吗?另外,无需在 itemView 中实现 render 并定义 tagName:'div' - 它的默认值。够了 - initialize:function () { this.model.on('fetch', this.render, this); this.model.fetch() }
  • @Evgeniy Plus there is no need to implement render in itemView - 你要我删除render 方法吗?那么如何将json传递给模板?
  • @3gwebtrain,是的,你可以删除它,木偶已经为你实现了它)
  • 如果你遵循我的第二条建议,你也可以摆脱那些废话 - var that = this

标签: node.js backbone.js marionette backbone-model


【解决方案1】:

正如我在 promise 'done' 回调中看到的,您只能获取结果,而不是模型。

请将您的初始化函数修改为:

initialize: function () {
    var that = this;
    this.model.fetch({
        success: function(model){
            that.render(model.toJSON());
        }
    });
}

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多